forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPairWiseSwap.java
48 lines (41 loc) · 1.25 KB
/
PairWiseSwap.java
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
package com.rampatra.linkedlists;
import com.rampatra.base.SingleLinkedList;
import com.rampatra.base.SingleLinkedNode;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/24/15
* @time: 3:48 PM
*/
public class PairWiseSwap {
/**
* Recursively swaps adjacent nodes of a linked list.
* <p/>
* Example:
* Input: 11->22->33->44->55
* Output: 22->11->44->33->55
*
* @param node
* @return new starting node after swapping adjacent nodes.
*/
public static <E extends Comparable<E>> SingleLinkedNode<E> pairWiseSwap(SingleLinkedNode<E> node) {
if (node == null || node.next == null) return node;
SingleLinkedNode<E> nextNode = node.next, nextOfNextNode = nextNode.next;
nextNode.next = node;
node.next = pairWiseSwap(nextOfNextNode);
return nextNode;
}
public static void main(String[] args) {
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
linkedList.add(11);
linkedList.add(22);
linkedList.add(33);
linkedList.add(44);
linkedList.add(55);
linkedList.add(66);
linkedList.add(77);
linkedList.printList();
linkedList.printList(pairWiseSwap(linkedList.head));
}
}