Singly Linked List Program in Java

A single linked list is a linear data structure in java program examples which each list member contains a pointer to the next element in the list. A node is a single element in a singly linked list. A pointer to the null is contained in the list’s last node. A singly linked list is a sort of unidirectional linked list that may only be traversed in one direction, from head to final node. A node is the name for each element in a linked list. A single node contains data as well as a pointer to the next node, which aids in the list’s structure.

public class Main 
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data = d; next=null;
}
}
public void display()
{
Node n = head;
while (n != null)
{
System.out.print(n.data+" \n");
n = n.next;
}
}
public static void main(String[] args)
{
Main list = new Main();
list.head = new Node(50);
Node second = new Node(100);
Node third = new Node(150);
list.head.next = second;
second.next = third;
list.display();
}
}

 

Output:

50

100

150

What is node head in java program examples

In Java, an Individual Node is a class that is used to build individual data holding blocks for a variety of data structures that organize data in a non-sequential manner. Because Node is a class, the value of next is always a reference – either to a Node or a subclass object, or to the null reference, which doesn’t refer to anything at all, and in which case the variable starts with a value of null.

Similar Programs