-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwapNodes.java
54 lines (53 loc) · 1.31 KB
/
SwapNodes.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
50
51
52
53
54
/********************************************************
> File Name:24SwapNodes.java
> Auther: ihochang
> Mail: [email protected]
> Created Time: Mon Jan 11 13:55:15 2016
*********************************************************/
public class SwapNodes {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = head;
ListNode left = head;
ListNode right = head.next;
ListNode temp;
left.next = right.next;
right.next = left;
head = right;
left = left.next;
if (right.next.next == null) {
return head;
} else
right = right.next.next.next;
while (left != null && right != null) {
//System.out.println(pre.val+" "+left.val+" "+right.val);
pre.next = right;
left.next = right.next;
right.next = left;
pre = pre.next.next;
left = left.next;
if (right.next.next == null) {
return head;
} else
right = right.next.next.next;
}
return head;
}
public static void main(String[] args) {
SwapNodes so = new SwapNodes();
ListNode l1 = new ListNode(0);
ListNode head1 = l1;
for (int i = 1;i<11;i++) {
l1.next = new ListNode(i);
l1 = l1.next;
}
l1 = head1.next;
ListNode answer = so.swapPairs(l1);
while(answer != null) {
System.out.print(answer.val+" ");
answer = answer.next;
}
}
}