-
Notifications
You must be signed in to change notification settings - Fork 19
/
SwapNodesInPairs.java
74 lines (61 loc) · 1.9 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package oj.leetcode;
public class SwapNodesInPairs {
public static ListNode createListFromArray(int[] arr) {
ListNode head = null;
for (int i = 0; i < arr.length; i++) {
ListNode node = new ListNode(arr[i]);
node.next = head;
head = node;
}
return head;
}
public static void showList(ListNode head) {
ListNode p = head;
while (p != null) {
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
}
public static ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0); // list header
dummy.next = head;
ListNode pre = dummy, p = head;
while (p != null && p.next != null) {
ListNode tmp = p.next;
p.next = p.next.next;
tmp.next = p;
pre.next = tmp;
pre = p;
p = p.next;
}
return dummy.next;
}
// �}ĿҪ��������������Ȼֱ�ӽ���ֵ����ӿ�
//You may not modify the values in the list, only nodes itself can be changed.
public static ListNode swapPairs2(ListNode head) {
ListNode p = head;
while (p != null && p.next != null) {
//swap(p.val, p.next.val);// ������������ΪJava�Ǵ�ֵ����
int tmp = p.val;
p.val = p.next.val;
p.next.val = tmp;
p = p.next.next;
}
return head;
}
public static void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
public static void main(String[] args) {
int[] arr = {1, 343, 45, 4, 6};
ListNode list = createListFromArray(arr);
showList(list);
list = swapPairs(list);
showList(list);
list = swapPairs2(list);
showList(list);
}
}