forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwapNodes.java
73 lines (61 loc) · 1.98 KB
/
SwapNodes.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.rampatra.linkedlists;
import com.rampatra.base.SingleLinkedList;
import com.rampatra.base.SingleLinkedNode;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 7/12/15
* @time: 1:23 PM
*/
public class SwapNodes {
/**
* Swap nodes with value {@param item1} with {@param item2} in linked list
* starting at {@param node}.
*
* @param node
* @param item1
* @param item2
* @param <E>
* @return
*/
public static <E extends Comparable<E>> SingleLinkedNode<E> swap(SingleLinkedNode<E> node,
E item1,
E item2) {
// dummy node needed to swap the very first node
SingleLinkedNode<E> head = new SingleLinkedNode<>(null),
curr1 = head,
curr2 = head,
temp;
head.next = node;
while (curr1.next != null && curr1.next.item != item1) {
curr1 = curr1.next;
}
while (curr2.next != null && curr2.next.item != item2) {
curr2 = curr2.next;
}
// if either of the node isn't present in the list then do nothing
if (curr1.next == null || curr2.next == null) return head.next;
// swap nodes
temp = curr1.next;
curr1.next = curr2.next;
curr2.next = temp;
// update their next nodes
temp = curr1.next.next;
curr1.next.next = curr2.next.next;
curr2.next.next = temp;
return head.next;
}
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(swap(linkedList.head, 111, 77));
}
}