-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthNode.java
More file actions
83 lines (61 loc) · 1.65 KB
/
RemoveNthNode.java
File metadata and controls
83 lines (61 loc) · 1.65 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
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class RemoveNthNode {
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = head;
int count = 1;
// length count karo
while (temp.next != null) {
count++;
temp = temp.next;
}
int k = count - n;
// agar first node delete karni ho
if (k == 0) {
return head.next;
}
ListNode temp2 = head;
for (int i = 1; i < k; i++) {
temp2 = temp2.next;
}
// node delete
temp2.next = temp2.next.next;
return head;
}
// linked list print karne ke liye
public static void printList(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
ListNode head = null;
ListNode tail = null;
// user se linked list input
for (int i = 0; i < size; i++) {
int val = sc.nextInt();
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
int n = sc.nextInt();
head = removeNthFromEnd(head, n);
printList(head);
}
}