Delete Element from Singly Linked List in Java

Java program to delete the linked list elements from a singly. This program will delete every element in the step by step by process in singly linked list. It will erase the linked list element in java program

public class Main
{
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public Node first = null;
public Node last = null;
public void addNode(int data)
{
Node newNode = new Node(data);
if(first == null)
{
first = newNode;
last = newNode;
}
else
{
last.next = newNode;
last = newNode;
}
}
public void deleteFromStart()
{

if(first == null)
{
System.out.println("List is empty");
return;
}
else
{

if(first != last) {
first = first.next;
}
else
{
first = last = null;
}
}
}
public void display()
{
Node current = first;
if(first == null) {
System.out.println("List is empty");
return;
}
while(current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}

public static void main(String[] args) {

Main sList = new Main();
sList.addNode(2);
sList.addNode(4);
sList.addNode(6);
sList.addNode(8);
System.out.println("Original List");
sList.display();
while(sList.first != null)
{
sList.deleteFromStart();
System.out.println("After list element deleted");
sList.display();
}
}
}

 

Output:

Original List
2 4 6 8
After list element deleted
4 6 8
After list element deleted
6 8
After list element deleted
8
After list element deleted
List is empty

What is linked list and how to delete list element in java

The Java collections framework’s Linked List class implements the linked list data structure’s features. A node is the name for each element in a linked list. The Linked List is a component of Java’s Collection framework. This class implements the Linked List data structure, which is a linear data structure in which the components are not stored in sequential order and each element is a separate object having a data and address part.

What is node in java

In Java, an Individual Node is a class used to build individual data holding blocks for various data structures that organize data in a non sequential manner.