-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathSwapNodesInPairs.java
More file actions
52 lines (43 loc) · 1.27 KB
/
Copy pathSwapNodesInPairs.java
File metadata and controls
52 lines (43 loc) · 1.27 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
/**
* Given a linked list, swap every two adjacent nodes and return its head.
* <p>
* For example,
* Given 1->2->3->4, you should return the list as 2->1->4->3.
* <p>
* Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
* <p>
* Accepted.
*/
public class SwapNodesInPairs {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = head, nxt = pre.next;
while (pre != null && nxt != null) {
int tmp = nxt.val;
nxt.val = pre.val;
pre.val = tmp;
pre = nxt.next;
if (pre != null) {
nxt = pre.next;
}
}
return head;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ListNode) {
ListNode node = (ListNode) obj;
return this.next == null && node.next == null || this.val == node.val && (this.next != null) && this.next.equals(node.next);
}
return false;
}
}
}