Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4476b30

Browse files
author
Ram swaroop
committed
pairwise swap: code improved
1 parent e69fc84 commit 4476b30

File tree

1 file changed

+9
-26
lines changed

1 file changed

+9
-26
lines changed

src/me/ramswaroop/linkedlists/PairWiseSwap.java

Lines changed: 9 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,43 +10,27 @@
1010
* @date: 6/24/15
1111
* @time: 3:48 PM
1212
*/
13-
public class PairWiseSwap<E extends Comparable<E>> extends SingleLinkedList<E> {
13+
public class PairWiseSwap {
1414

1515
/**
1616
* Recursively swaps adjacent nodes of a linked list.
1717
* The swapping is done in place.
1818
*
1919
* @param node
2020
*/
21-
public void pairWiseSwap(SingleLinkedNode<E> node) {
22-
if (node == null || node.next == null) return;
21+
public static <E extends Comparable<E>> SingleLinkedNode<E> pairWiseSwap(SingleLinkedNode<E> node) {
22+
if (node == null || node.next == null) return node;
2323

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;
24+
SingleLinkedNode<E> nextNode = node.next, nextOfNextNode = nextNode.next;
2825

29-
if (firstNode == null || secondNode == null) return;
26+
nextNode.next = node;
27+
node.next = pairWiseSwap(nextOfNextNode);
3028

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);
29+
return nextNode;
4630
}
4731

4832
public static void main(String a[]) {
49-
PairWiseSwap<Integer> linkedList = new PairWiseSwap<>();
33+
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
5034
linkedList.add(11);
5135
linkedList.add(22);
5236
linkedList.add(33);
@@ -55,7 +39,6 @@ public static void main(String a[]) {
5539
linkedList.add(66);
5640
linkedList.add(77);
5741
linkedList.printList();
58-
linkedList.pairWiseSwap();
59-
linkedList.printList();
42+
linkedList.printList(pairWiseSwap(linkedList.head));
6043
}
6144
}

0 commit comments

Comments
 (0)