forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwapKthNode.java
75 lines (59 loc) · 1.98 KB
/
SwapKthNode.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
74
75
package com.rampatra.linkedlists;
import com.rampatra.base.SingleLinkedList;
import com.rampatra.base.SingleLinkedNode;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 7/13/15
* @time: 12:25 PM
*/
public class SwapKthNode {
public static <E extends Comparable<E>> SingleLinkedNode<E> swapKthNodeFromStartWithKthNodeFromEnd(SingleLinkedNode<E> node,
int k) {
int i = 1;
// dummy node needed to swap the very first node
SingleLinkedNode<E> head = new SingleLinkedNode<>(null),
curr = head,
slow = head,
fast = head,
temp;
head.next = node;
// find kth node from start
while (i < k && curr.next != null) {
curr = curr.next;
fast = fast.next;
i++;
}
// move the fast pointer k steps ahead of slow
fast = fast.next;
// find kth node from end
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
// if either of the node isn't present in the list then do nothing
if (curr.next == null || slow.next == null) return head.next;
// swap nodes
temp = curr.next;
curr.next = slow.next;
slow.next = temp;
// update their next nodes
temp = curr.next.next;
curr.next.next = slow.next.next;
slow.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(swapKthNodeFromStartWithKthNodeFromEnd(linkedList.head, 2));
}
}