-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1_LL.java
More file actions
59 lines (49 loc) · 1.37 KB
/
Q1_LL.java
File metadata and controls
59 lines (49 loc) · 1.37 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
class Node111 {
int data;
Node111 next;
Node111(int data) {
this.data = data;
this.next = null;
}
}
public class Q1_LL {
public static void traversal(Node111 head) {
Node111 curr = head;
while (curr != null) {
System.out.println(curr.data);
curr = curr.next;
}
}
public static Node111 deletion(Node111 head, int pos) {
int size = 0;
Node111 curr = head;
while (curr != null) {
size++;
curr = curr.next;
}
if (pos == size) {
return head.next; /// this code is not working
}
Node111 prev = head;
int NodePos = (size - pos) + 1;
for (int i = 1; i < NodePos - 1; i++) {
prev = prev.next;
}
prev.next = prev.next.next;
return head;
}
public static void main(String[] args) {
// Search and delete nth Node from the last of linked list;
Node111 n1 = new Node111(1);
Node111 n2 = new Node111(2);
Node111 n3 = new Node111(3);
Node111 n4 = new Node111(4);
Node111 head = n1;
head.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = null;
deletion(head, 4);// pass head and element no.
traversal(head);
}
}