0 0
Read Time:52 Second

Singly Linked List Implementation Using Java

First, we need to create Node and each node we will store in a singly linked list. Each Node contains two fields, the first field contains data and the second field contains a link to the next node.

Create Node

Following is a type declaration for a linked list:

/**
 * Class demonstrates the declaration for a linked list.
 * @author Gaurav Dixit
 *
 */
public class ListNode{
    public ListNode next;
    public int data;

    // Creates an empty node.
    public ListNode(){
        next = null;
        data = Integer.MIN_VALUE;
    }

    // Creates a node storing the specified data.
    public ListNode (int data){
        next = null;
        this.data = data;
    }

    // Returns the node that follows this one.
    public ListNode getNext(){
        return next;
    }

    // Sets the node that follows this one.
    public void setNext (ListNode node){
        next = node;
    }

    // Returns the data stored in this node.
    public int getData(){
        return data;
    }

    // Sets the data stored in this node.
    public void setdata (int elem){
        data = elem;
    }
 
    // Sets the data stored in this node.
    public String toString (){
        return Integer.toString(data);
    } 
}
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Verified by MonsterInsights