Linked List: Program to delete a node from linked list
Write a program to delete a node from the linked list
Linked list is a series of nodes in which each node contains a data field and
reference (pointer) to the next node in the list.
There are two cases for deleting a node from a linked list
-
Deleting the node from the start of the linked list
- For deleting node from the start, we have to simply make head as head.next
-
Deleting the node from the end of linked list
- To delete node at the end we can refer the following steps
- Create a pointer 'current' and set on the head
- While current.next.next is not NULL, make current as current.next
- After the loop terminates, make current.next as NULL to remove the last node
Complexity
Time Complexity : O(n) , where n is the size of linked list
Space Complexity : O(1)
Java Code
import java.util.*;
class Node {
// initialising data field and next pointer of node
int data;
Node next;
Node(int d) {
this.data = d;
this.next = null;
}
}
class LinkedList {
Node head;
// creating a linked list using array
public void buildLinkedlist(int A[], int noOfNodes) {
int i;
Node temp, last;
temp = new Node(A[0]);
temp.next = null;
head = temp;
last = temp;
for (i = 1; i < noOfNodes; i++) {
temp = new Node(A[i]);
temp.next = null;
last.next = temp;
last = temp;
}
}
// printing of linkedList
public void printLinkedlist() {
List allNodesList = new ArrayList<>();
Node temp = head;
while (temp != null) {
allNodesList.add(Integer.toString(temp.data));
temp = temp.next;
}
System.out.println(String.join(" -> ", allNodesList));
}
// deleting node from start
public void deleteStartNode() {
Node current = head;
head = head.next;
current.next = null;
}
// deleting node from end
public void deleteEndNode() {
if (head == null)
return;
Node current = head;
if (current.next == null) {
head = null;
}
while (current.next.next != null) {
current = current.next;
}
current.next = null;
}
public static void main(String[] args) {
int[] linkedlistElements = new int[] { 10 };
int numberOfNodes = 1;
// Initializing object of linkedlist class
LinkedList ll = new LinkedList();
ll.buildLinkedlist(linkedlistElements, numberOfNodes);
System.out.println("Given Linked List ");
ll.printLinkedlist();
System.out.println("Linked List after deleting first node");
ll.deleteStartNode();
ll.printLinkedlist();
System.out.println("Linked List after deleting last node");
ll.deleteEndNode();
ll.printLinkedlist();
}
}
Output
Given Linked List
10 -> 30 -> 50 -> 40 -> 70 -> 90
Linked List after deleting first node
30 -> 50 -> 40 -> 70 -> 90
Linked List after deleting last node
30 -> 50 -> 40 -> 70
Thanks for feedback.