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

Commit 2241912

Browse files
author
Ram swaroop
committed
nth node from last done
1 parent bd215ca commit 2241912

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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: 6/18/15
11+
* @time: 6:49 PM
12+
*/
13+
public class NthNodeFromLast<E> extends SingleLinkedList<E> {
14+
15+
public SingleLinkedNode<E> getNthNodeFromLast(SingleLinkedNode<E> node, int n) {
16+
SingleLinkedNode<E> slow = node;
17+
SingleLinkedNode<E> fast = node;
18+
// move the fast reference ahead of slow reference by 'n' nodes
19+
for (int i = 0; i < n; i++) {
20+
// assert length of linkedlist > n
21+
fast = fast.next;
22+
}
23+
while (fast != null) {
24+
slow = slow.next;
25+
fast = fast.next;
26+
}
27+
return slow;
28+
}
29+
30+
public static void main(String a[]) {
31+
NthNodeFromLast<Integer> linkedList = new NthNodeFromLast<>();
32+
linkedList.add(11);
33+
linkedList.add(22);
34+
linkedList.add(33);
35+
linkedList.add(44);
36+
linkedList.add(55);
37+
linkedList.add(66);
38+
linkedList.add(77);
39+
linkedList.add(88);
40+
System.out.println(linkedList.getNthNodeFromLast(linkedList.getNode(0), 3).item);
41+
}
42+
}

0 commit comments

Comments
 (0)