This repository has been archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathRemoveNthNodeFromLast.java
97 lines (62 loc) · 1.92 KB
/
RemoveNthNodeFromLast.java
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*-- Removing Bth node from the bottom of a LinkedList --*/
import java.util.*;
public class RemoveNthNodeFromLast {
static Node removeNthFromLast(Node A, int B) {
if(A.next==null)
return null;
int count = 0;
Node n = A;
Node AA = A; /*-- We have to always keep the reference of the Head. --*/
//We are just traversing here, not changing anything!
while(n!=null){
n = n.next;
count++;
}
int x = count-B;
if(x==0)
return AA.next;
/*-- We are not looping A(Head) beacasue otherwise we loose the pointer to the Head,
that's why taking the reference of A into AA and looping AA --*/
for(int i=1; i<x; i++){
AA = AA.next;
}
if(AA.next.next!=null)
AA.next = AA.next.next;
else
AA.next = null;
return A;
}
/*-- Inputs from the main method --*/
public static void main(String[] args){
Node A = new Node(5);
A.addNodeToTail(10);
A.addNodeToTail(20);
A.addNodeToTail(30);
A.addNodeToTail(35);
A.addNodeToTail(40);
A.addNodeToTail(50);
Node C = removeNthFromLast(A, 5);
while(C!=null){
System.out.println(C.data);
C = C.next;
}
}
}
/*-- Node class Implementation --*/
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
public void addNodeToTail(int addData){
Node current = this;
while(current!=null){
if(current.next==null){
current.next = new Node(addData);
break;
}
current = current.next;
}
}
}