-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSwapInPairs.java
More file actions
30 lines (23 loc) · 816 Bytes
/
SwapInPairs.java
File metadata and controls
30 lines (23 loc) · 816 Bytes
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
package swe.LinkedList;
public class SwapInPairs {
public Node swapPairs(Node head) {
// 1 -> 2 -> 3 -> 4 -> x
if (head == null || head.next == null) {
return head;
}
Node dummyNode = new Node(0);
dummyNode.next = head; // 0 -> 1 -> 2 -> 3 -> 4 -> x
Node previousNode = dummyNode; // previousNode = 0
while (head != null && head.next != null) {
Node first = head; // first = 1
Node second = head.next; // second = 2
first.next = second.next;
second.next = first;
previousNode = first;
previousNode.next = second;
head = first.next;
}
return dummyNode.next;
// Output : 2 -> 1 -> 4 -> 3 -> x
}
}