Skip to content

Commit df51cd4

Browse files
author
Ram swaroop
committed
pair wise swap: done
1 parent f5b1049 commit df51cd4

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package me.ramswaroop.linkedlists;
2+
3+
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 6/24/15
11+
* @time: 3:48 PM
12+
*/
13+
public class PairWiseSwap<E extends Comparable<E>> extends SingleLinkedList<E> {
14+
15+
/**
16+
* Recursively swaps adjacent nodes of a linked list.
17+
* The swapping is done in place.
18+
*
19+
* @param node
20+
*/
21+
public void pairWiseSwap(SingleLinkedNode<E> node) {
22+
if (node == null || node.next == null) return;
23+
24+
// the trick is to swap the next two nodes of {@param node}
25+
// but if {@param node} is head then swap itself with the next node
26+
SingleLinkedNode<E> firstNode = (node == head) ? node : node.next,
27+
secondNode = (node == head) ? node.next : node.next.next;
28+
29+
if (firstNode == null || secondNode == null) return;
30+
31+
firstNode.next = secondNode.next;
32+
secondNode.next = firstNode;
33+
34+
if (node == head) {
35+
head = secondNode;
36+
} else {
37+
node.next = secondNode;
38+
}
39+
40+
// pass firstNode as the next two nodes are swapped
41+
pairWiseSwap(firstNode);
42+
}
43+
44+
public void pairWiseSwap() {
45+
pairWiseSwap(head);
46+
}
47+
48+
public static void main(String a[]) {
49+
PairWiseSwap<Integer> linkedList = new PairWiseSwap<>();
50+
linkedList.add(11);
51+
linkedList.add(22);
52+
linkedList.add(33);
53+
linkedList.add(44);
54+
linkedList.add(55);
55+
linkedList.add(66);
56+
linkedList.add(77);
57+
linkedList.printList();
58+
linkedList.pairWiseSwap();
59+
linkedList.printList();
60+
}
61+
}

0 commit comments

Comments
 (0)