Deletion is an important operation in a linked list that involves removing nodes from the list. There are various approaches to deleting elements from a linked list, depending on the position of the node to be deleted and the desired behavior of the list.
1. Deleting at the beginning
To delete the first node of a linked list, we simply update the head
to point to the next node.
1public void deleteAtBeginning() {
2 if (head != null) {
3 head = head.next;
4 }
5}
2. Deleting at the end
To delete the last node of a linked list, we need to traverse the list until we reach the second-to-last node. Then, we update the next
field of the second-to-last node to null
.
1public void deleteAtEnd() {
2 if (head == null || head.next == null) {
3 head = null;
4 } else {
5 Node current = head;
6 while (current.next.next != null) {
7 current = current.next;
8 }
9 current.next = null;
10 }
11}
3. Deleting at a specific position
To delete a node at a specific position within a linked list, we need to traverse the list until we reach the position-1. Then, we update the next
field of the previous node to skip the node to be deleted.
1public void deleteAtPosition(int position) {
2 if (position == 0) {
3 deleteAtBeginning();
4 } else {
5 Node current = head;
6 for (int i = 0; i < position - 1 && current != null; i++) {
7 current = current.next;
8 }
9 if (current != null && current.next != null) {
10 current.next = current.next.next;
11 }
12 }
13}
These are some basic methods for deleting elements from a linked list. Depending on the situation and requirements, additional logic may be needed to handle special cases, such as deleting multiple occurrences of a value or deleting nodes based on specific conditions.
By using these methods, you can effectively delete elements from a linked list and maintain the structure as needed. It's important to consider the time and space complexity of each method when performing deletions, especially in scenarios involving large lists or performance-critical applications.
xxxxxxxxxx
}
public void deleteAtBeginning() {
if (head != null) {
head = head.next;
}
}
public void deleteAtEnd() {
if (head == null || head.next == null) {
head = null;
} else {
Node current = head;
while (current.next.next != null) {
current = current.next;
}
current.next = null;
}
}
public void deleteAtPosition(int position) {
if (position == 0) {
deleteAtBeginning();
} else {
Node current = head;
for (int i = 0; i < position - 1 && current != null; i++) {
current = current.next;
}
if (current != null && current.next != null) {
current.next = current.next.next;
}