算法笔记-两两交换链表相邻节点

2024-04-09

# 两两交换链表相邻节点

前言: 两两交换这个模拟过程 我总是不知道 我是要定义 pre 和 cur 还是 cur 和 next 指针 可能两种方式都可以 但如果定义了虚拟头结点 dummy(我习惯写成 StartHead 了)那可能前者更好 因为 next 这个临时节点 可以在 while 里面(伴随判断定义)

# 题目 (中等)

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

img
img

1
2
输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

1
2
输入:head = []
输出:[]

示例 3:

1
2
输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100

先看看我的垃圾错误解答吧。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Solution {


public ListNode SwapPairs(ListNode head) {
//虚拟头节点
ListNode startHead = new();
startHead.next = head;
ListNode cur = new();
ListNode next = new(); 定义了太多没用的变量 混乱 要想清楚再写啊。。。
ListNode temp;

cur = head;

//如果为空链表 或者 就一个头节点
if(cur == null || cur.next == null){
return cur;
}
else{
next = cur.next;
}

//这里 cur.next 为头节点

while(next != null) 我这里的判断情况就漏掉了奇数的情况 链表长度为奇数的时候 这里就会报错
1 2 3 4 5 -》 2 1 4 3 5 ,,,
{
//第一次交换 评价: (其实如果while 里有这种判断 感觉就已经gg了)
if(startHead.next == cur)
{
startHead.next = next;
}

temp = next.next; //先保存一下后面节点的next
next.next = cur;
cur.next = temp;

if(temp.next == null){
return startHead.next;
}
next = temp.next; //如果空了 直接

cur = cur.next; //这里也没正确更新?
next = temp.next;
}

return startHead.next;

}
}

修正过后

# 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {


public ListNode SwapPairs(ListNode head) {
//如果为空链表 或者 就一个头节点
if(head == null || head.next == null){
return head;
}
//虚拟头节点
ListNode startHead = new();
startHead.next = head;
ListNode cur = head;
ListNode pre = startHead;
//这里 cur.next 为头节点

while(cur != null && cur.next != null)
{
ListNode nextNode = cur.next;
ListNode temp = nextNode.next;

pre.next = nextNode;
nextNode.next = cur;
cur.next = temp;


pre = cur;
cur = temp;
}

return startHead.next;

}
}