-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNthNodeFromEnd.java
More file actions
46 lines (37 loc) · 968 Bytes
/
Copy pathNthNodeFromEnd.java
File metadata and controls
46 lines (37 loc) · 968 Bytes
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
package com.rrohit.algo.linkedlist;
/*
* @author rrohit
*/
public class NthNodeFromEnd {
public <T>Node<T> findNthNodeFromEnd(Node<T> head, int n) {
if (head == null) {
return null;
}
Node<T> nthNode = head, current = head;
int count = 1;
while (count < n) {
current = current.getNext();
if (current == null) {
System.out.println("Inavlid n :: "+n+" size of Linked List = "+count);
return null;
}
count++;
}
while (current.getNext() != null) {
nthNode = nthNode.getNext();
current = current.getNext();
}
return nthNode;
}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i=1; i<10; i++) {
list.add(i);
}
list.display();
NthNodeFromEnd nth = new NthNodeFromEnd();
Node node = nth.findNthNodeFromEnd(list.getHead(), 10);
System.out.println("3rd Node from End = "+node);
System.out.println("Size = "+list.getSize());
}
}