-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSwapNodesinPairs.java
49 lines (43 loc) · 1.21 KB
/
SwapNodesinPairs.java
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
/**
* Created by cpacm on 2017/5/9.
*/
public class SwapNodesinPairs {
public static void main(String[] args) {
ListNode head = new ListNode(8);
head.next = new ListNode(12);
head.next.next = new ListNode(10);
head.next.next.next = new ListNode(15);
head.next.next.next.next = new ListNode(17);
head.next.next.next.next.next = new ListNode(20);
System.out.println(swapPairs(head));
}
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode v = new ListNode(-1);
v.next = head;
ListNode res = v;
while (v.next != null && v.next.next != null) {
ListNode temp = v.next;
ListNode l1 = temp.next;
ListNode l2 = temp.next.next;
l1.next = temp;
temp.next = l2;
v.next = l1;
v = v.next.next;
}
return res.next;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
@Override
public String toString() {
return val + "";
}
}
}