10
10
* @date: 6/24/15
11
11
* @time: 3:48 PM
12
12
*/
13
- public class PairWiseSwap < E extends Comparable < E >> extends SingleLinkedList < E > {
13
+ public class PairWiseSwap {
14
14
15
15
/**
16
16
* Recursively swaps adjacent nodes of a linked list.
17
17
* The swapping is done in place.
18
18
*
19
19
* @param node
20
20
*/
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 ;
23
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 ;
24
+ SingleLinkedNode <E > nextNode = node .next , nextOfNextNode = nextNode .next ;
28
25
29
- if (firstNode == null || secondNode == null ) return ;
26
+ nextNode .next = node ;
27
+ node .next = pairWiseSwap (nextOfNextNode );
30
28
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 ;
46
30
}
47
31
48
32
public static void main (String a []) {
49
- PairWiseSwap <Integer > linkedList = new PairWiseSwap <>();
33
+ SingleLinkedList <Integer > linkedList = new SingleLinkedList <>();
50
34
linkedList .add (11 );
51
35
linkedList .add (22 );
52
36
linkedList .add (33 );
@@ -55,7 +39,6 @@ public static void main(String a[]) {
55
39
linkedList .add (66 );
56
40
linkedList .add (77 );
57
41
linkedList .printList ();
58
- linkedList .pairWiseSwap ();
59
- linkedList .printList ();
42
+ linkedList .printList (pairWiseSwap (linkedList .head ));
60
43
}
61
44
}
0 commit comments