-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleLinkedList_Deletion.java
More file actions
120 lines (98 loc) · 2.9 KB
/
Copy pathSingleLinkedList_Deletion.java
File metadata and controls
120 lines (98 loc) · 2.9 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
package datastructures;
public class SingleLinkedList_Deletion {
public static void main(String[] args) {
// TODO Auto-generated method stub
SingleLinkedList_Deletion list = new SingleLinkedList_Deletion();
// Insertion at the beginning
list.insertAtBeginning(5);
list.insertAtBeginning(3);
// Insertion at the end
list.insertAtEnd(7);
list.insertAtEnd(9);
// Deletion at the beginning
list.deleteAtBeginning();
// Deletion at the end
list.deleteAtEnd();
// Insertion at the end
list.insertAtEnd(11);
// Deletion at specific location
list.deleteAtLocation(1);
// Print the linked list
list.printList();
}
Node head;
SingleLinkedList_Deletion() {
this.head = null;
}
// Insertion at the beginning
void insertAtBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Deletion at the beginning
void deleteAtBeginning() {
if (head == null) {
System.out.println("List is empty. Nothing to delete.");
return;
}
head = head.next;
}
// Insertion at the end
void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
// Deletion at the end
void deleteAtEnd() {
if (head == null) {
System.out.println("List is empty. Nothing to delete.");
return;
}
if (head.next == null) {
head = null;
return;
}
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
// Deletion at a specific location
void deleteAtLocation(int position) {
if (head == null) {
System.out.println("List is empty. Nothing to delete.");
return;
}
if (position == 0) {
head = head.next;
return;
}
Node temp = head;
for (int i = 0; temp != null && i < position - 1; i++) {
temp = temp.next;
}
if (temp == null || temp.next == null) {
return;
}
temp.next = temp.next.next;
}
// Utility function to print the linked list
void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}