-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-24.java
More file actions
62 lines (53 loc) · 1.43 KB
/
lc-24.java
File metadata and controls
62 lines (53 loc) · 1.43 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
//非常有意义的错误,尚且不知道错在哪里了
class Solution {
public ListNode swapPairs(ListNode head) {
//交换
ListNode res = head;
while(res != null && res.next != null) {
ListNode t = res.next;
res.next = t.next;
t.next = res;
res = res.next;
}
return head;
}
}
//我自己的ac方案
class Solution {
public ListNode swapPairs(ListNode head) {
//交换
ListNode nh = new ListNode(0);
ListNode res = nh;
while(head != null && head.next != null) {
head = swap(head);
nh.next = head;
nh = nh.next.next;
head = head.next.next == null?null:head.next.next;
}
return res.next;
}
private ListNode swap(ListNode n) {
ListNode t = n.next;
n.next = t.next;
t.next = n;
return t;
}
}
//参考答案
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode pre = new ListNode(0), temp = head, suf;
//一个前置空表头
head = pre;
while (temp != null && temp.next != null){
pre.next = temp.next;
suf = temp.next.next;
temp.next.next = temp;
temp.next = suf;
pre = temp;
temp = temp.next;
}
return head.next;
}