-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_03.java
More file actions
91 lines (70 loc) · 1.7 KB
/
Copy pathLinked_List_03.java
File metadata and controls
91 lines (70 loc) · 1.7 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
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
// Find the nth node from the end & remove it.
class Linked_List{
Node head;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public void Add(int val){
Node new_Node=new Node(val);
if(head==null){
head=new_Node;
return;
}
Node curr=head;
while(curr.next!=null){
curr=curr.next;
}
curr.next=new_Node;
return;
}
public void Print_List(){
Node curr=head;
while(curr!=null){
System.out.print(curr.data + " -> ");
curr=curr.next;
}
System.out.println("NULL");
}
public Node Remove_nth_from_end(Node head,int n){
if(head==null || head.next==null){
head=null;
return head;
}
Node slow=head;
Node fast=head;
while(n>0){
fast=fast.next;
n--;
}
// If fast is null after moving n steps,
// it means we need to remove the head node itself.
if (fast == null) {
return head.next;
}
while(fast.next!=null){
slow=slow.next;
fast=fast.next;
}
slow.next=slow.next.next;
return head;
}
}
public class Linked_List_03 {
public static void main(String[] args){
Linked_List list=new Linked_List();
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Print_List();
list.head = list.Remove_nth_from_end(list.head,3);
list.Print_List();
}
}