-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay 65 Deletion in circular LinkedList
More file actions
146 lines (127 loc) · 3.24 KB
/
Copy pathDay 65 Deletion in circular LinkedList
File metadata and controls
146 lines (127 loc) · 3.24 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
public class Main {
public static void main(String[] args) {
Main Obj = new Main();
Obj.add(10);
Obj.add(20);
Obj.add(30);
Obj.add(40);
Obj.add(50);
Obj.add(60);
System.out.println("List Before Deletion");
Obj.print();
System.out.println("List After Deleting first node");
Obj.deleteFirst();
Obj.print();
System.out.println("List After Deleting last node");
Obj.deleteLast();
Obj.print();
Obj.deleteNthNode(2);
System.out.println("List After Deleting 2nd node");
Obj.print();
}
public class Node{
int element;
Node next;
public Node(int element) {
this.element = element;
}
}
public Node head = null;
public Node tail = null;
public void print() {
Node temp = head;
if(head == null) {
System.out.println("null");
}
else {
do{
System.out.print(" "+ temp.element);
temp = temp.next;
}while(temp != head);
System.out.println();
}
}
public void add(int element){
Node newNode = new Node(element);
if(head == null) {
head = newNode;
tail = newNode;
newNode.next = head;
}
else {
tail.next = newNode;
tail = newNode;
tail.next = head;
}
}
public void deleteFirst() {
if(head == null) {
return;
}
else {
if(head != tail ) {
head = head.next;
tail.next = head;
}
else {
head = tail = null;
}
}
}
public void deleteLast() {
if(head == null) {
return;
}
else {
if(head != tail ) {
Node current = head;
while(current.next != tail) {
current = current.next;
}
tail = current;
tail.next = head;
}
else {
head = tail = null;
}
}
}
public int calcLen(){
int len = 0;
Node temp=head;
while(temp!=tail){
temp = temp.next;
len++;
}
return len;
}
public void deleteNthNode(int n)
{
int len = calcLen();
// Can only insert after 1st position
// Can't insert if position to insert is greater than size of Linked List
if(n < 1 || n > len)
{
System.out.println("Can't delete\n");
}
else
{
if(n == 1)
{
head = head.next;
return;
}
// required to traverse
Node temp = head;
Node previous = null;
// traverse to the nth node
while(--n > 0) {
previous = temp;
temp = temp.next;
}
// assigned next node of the previous node to nth node's next
previous.next = temp.next;
System.out.println("Deleted: " + temp.element);
}
}
}