-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathRemoveNthNodeFromEndVVI.java
81 lines (67 loc) · 1.48 KB
/
RemoveNthNodeFromEndVVI.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
/*
* Fint & Remove Nth node from End ( Iterative Approach ).
*/
public class RemoveNthNodeFromEndVVI {
public static class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public static Node head,tail;
// add First
public static void addFirst(int data) {
Node nextNode =new Node(data);
if (head==null) {
head=tail=nextNode;
return;
}
nextNode.next=head;
head=nextNode;
}
// Print Linked List
public static void printLL(){
Node temp = head;
while (temp!=null) {
System.out.print(temp.data + " ");
temp=temp.next;
}
System.out.println();
}
// Remove Nth node from End
public static void removeN(int n){
// Size of Linked list
int size=0;
Node prev,temp;
prev= temp = head;
while(temp!=null){
temp=temp.next;
size++;
}
int indx = size-n-1;
int i=0;
while(i<indx){
prev=prev.next;
i++;
}
prev.next = prev.next.next;
return;
}
public static void main(String[] args) {
addFirst(5);
addFirst(4);
addFirst(3);
addFirst(2);
addFirst(1);
printLL();
removeN(3);
printLL();
}
}
/*
* Output
* 1 2 3 4 5
* 1 2 4 5
*/