File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments