- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindNthElementsFromLastExample.java
More file actions
Latest commit
42 lines (38 loc) · 1.11 KB
/
Copy pathFindNthElementsFromLastExample.java
File metadata and controls
42 lines (38 loc) · 1.11 KB
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
packagecom.codinginterview;
publicclassFindNthElementsFromLastExample {
publicstaticvoidmain(String[] args) {
System.out.println("Find nth Elements from last");
NodeFnodeF = newNodeF(1);
nodeF.next = newNodeF(2);
nodeF.next.next = newNodeF(3);
nodeF.next.next.next = newNodeF(4);
nodeF.next.next.next.next = newNodeF(5);
NodeFresult = findnthElementFromLast(nodeF, 6);
if(result != null){
System.out.println(result.value);
}else{
System.out.println("Wrong item to find!!");
}
}
privatestaticNodeFfindnthElementFromLast(NodeFroot, intn){
NodeFcurr = root;
NodeFfollower = root;
for(inti = 0; i< n-1; i++){
if(curr == null ) returnnull;
curr = curr.next;
}
if(curr == null) returnnull;
while(curr.next != null){
curr = curr.next;
follower = follower.next;
}
returnfollower;
}
}
classNodeF{
intvalue;
NodeFnext;
NodeF(intvalue){
this.value = value;
}
}