Site icon

Delete /remove all nodes of a single linked list in java (example/non-recursive)

Fig 1: Delete single linked list

Algorithm – delete/remove all nodes of a single linked list in java

delete remove node single linked list
Fig 2: Delete head node of single linked list

Time complexity of algorithm is O(n).

Program – Delete/remove all nodes of single linked list in java.

1.) DeleteLinkedList Class:

package org.learn.Question;

import org.learn.List.Node;

public class DeleteLinkedList {

	public static Node delete(Node head) {
		Node backup = null;
		while (head != null) {
			backup = head.next;
			head = null;
			head = backup;
		}
		return head;
	}

	public static void insert(Node head, int data) {
		while (head.next != null)
			head = head.next;
		head.next = new Node(data);
	}

	public static void print(Node head) {
		while (head != null) {
			System.out.printf("%d ", head.data);
			head = head.next;
		}
		System.out.println("");
	}
}

2.) App Class:

package org.learn.Client;

import org.learn.List.Node;
import org.learn.Question.DeleteLinkedList;

public class App {
	public static void main(String[] args) {
		int[] data = { 9, 5, 2, 8, 10, 9, 1 };
		Node head = new Node(data[0]);
		for (int count = 1; count < data.length; count++)
			DeleteLinkedList.insert(head, data[count]);

		System.out.printf("Linked list is : ");
		DeleteLinkedList.print(head);

		head = DeleteLinkedList.delete(head);
		if (head == null) {
			System.out.println("Deleted all nodes in linked list");
		} else {
			System.out.println("Could not able to delete all nodes from linked list");
		}
	}
}

3.) Node Class:

package org.learn.List;

public class Node {
	public int data;
	public Node next;

	public Node(int num) {
		this.data = num;
		this.next = null;
	}
}

Output – delete/remove all nodes of  a single linked list in java

Linked list is : 10 20 10 20 50 20 50
Deleted all nodes in linked list

Download code – delete/ remove all nodes of single linked list in java

 

 

Exit mobile version