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

Commit 09bb070

Browse files
author
Ram swaroop
committed
swap kth node from start with kth node from end in linked list: done
1 parent a55337c commit 09bb070

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package me.ramswaroop.linkedlists;
2+
3+
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 7/13/15
11+
* @time: 12:25 PM
12+
*/
13+
public class SwapKthNode {
14+
15+
public static <E extends Comparable<E>> SingleLinkedNode<E> swapKthNodeFromStartWithKthNodeFromEnd(SingleLinkedNode<E> node,
16+
int k) {
17+
18+
19+
int i = 1;
20+
21+
// dummy node needed to swap the very first node
22+
SingleLinkedNode<E> head = new SingleLinkedNode<>(null),
23+
curr = head,
24+
slow = head,
25+
fast = head,
26+
temp;
27+
28+
head.next = node;
29+
30+
// find kth node from start
31+
while (i < k && curr.next != null) {
32+
curr = curr.next;
33+
fast = fast.next;
34+
i++;
35+
}
36+
37+
// move the fast pointer k steps ahead of slow
38+
fast = fast.next;
39+
40+
// find kth node from end
41+
while (fast.next != null) {
42+
slow = slow.next;
43+
fast = fast.next;
44+
}
45+
46+
// if either of the node isn't present in the list then do nothing
47+
if (curr.next == null || slow.next == null) return head.next;
48+
49+
// swap nodes
50+
temp = curr.next;
51+
curr.next = slow.next;
52+
slow.next = temp;
53+
54+
// update their next nodes
55+
temp = curr.next.next;
56+
curr.next.next = slow.next.next;
57+
slow.next.next = temp;
58+
59+
return head.next;
60+
61+
}
62+
63+
public static void main(String a[]) {
64+
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
65+
linkedList.add(11);
66+
linkedList.add(22);
67+
linkedList.add(33);
68+
linkedList.add(44);
69+
linkedList.add(55);
70+
linkedList.add(66);
71+
linkedList.add(77);
72+
linkedList.printList();
73+
linkedList.printList(swapKthNodeFromStartWithKthNodeFromEnd(linkedList.head, 2));
74+
}
75+
}

0 commit comments

Comments
 (0)