Skip to content

Commit 18fafd6

Browse files
author
Li Li
committed
add code of 24
1 parent 8f5380d commit 18fafd6

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class Solution {
2+
public ListNode SwapPairs(ListNode head) {
3+
if (head == null || head.next == null) return head;
4+
ListNode dummy = new ListNode(0);
5+
dummy.next = head;
6+
ListNode pre = dummy, temp = null;
7+
while (head != null && head.next != null) {
8+
ListNode n1 = head, n2 = head.next;
9+
// head
10+
// pre -> n1 -> n2 -> temp...
11+
// pre -> n2 -> n1 -> temp...
12+
temp = n2.next;
13+
pre.next = n2;
14+
n2.next = n1;
15+
n1.next = temp;
16+
// n2 -> pre-> head
17+
// move to next pair, ...-> n2 -> n1 -> temp ...
18+
pre = pre.next.next;
19+
head = temp;
20+
}
21+
return dummy.next;
22+
}
23+
}

0 commit comments

Comments
 (0)