Create a Singly Linked List in Java

A Singly Linked List is a collection of nodes in a linear sequence. Furthermore, each node stores two things:

  1. Data
  2. A reference to the next node
Singly Linked List
package com.java.datastructure;
public class SinglyLinkedList {
	
	private Node head;
	private Node tail;
	
	// Adds the element as the head
	public void addToFirst(String data) {		
		  if(head == null) {
			  head = new Node(data, null);
			  tail = head;
		  }else {
			  Node newNode = new Node(data, head);
			  head = newNode;
		  }
		}
	
	// Adds the element as the tail
	public void addToLast(String data) {		
	  if(head == null) {
		  head = new Node(data, null);
		  tail = head;
	  }else {
		  Node newNode = new Node(data, null);
		  tail.setNext(newNode);
		  tail = newNode;
	  }
	}
	
	public void traverse() {
		if(head == null) {
			System.out.println("No elements in the SinglyLinkedList");
			return;
		}
		Node node = head;
		int i =0;
		while(node != null) {
			if( i > 0) {
				System.out.print(" ==> ");
			}
			System.out.print(node);
			node = node.getNext();
			i++;
		}
	}
	
	public static void main(String[] args) {
		SinglyLinkedList linkedList = new SinglyLinkedList();
		linkedList.addToLast("Rochit");
		linkedList.addToLast("Gyan");
		linkedList.addToLast("Praveen");
		linkedList.addToFirst("Vivek");
		linkedList.traverse();
	}
}
class Node{
	public String getData() {
		return data;
	}
	public Node getNext() {
		return next;
	}
	public Node(String data, Node next) {
		this.data = data;
		this.next = next;
	}
	public void setData(String data) {
		this.data = data;
	}
	public void setNext(Node next) {
		this.next = next;
	}
	@Override
	public String toString() {
		if(next != null) {
		return "Node [data=" + data + ", next=" + next.getData() + "]";
		}
		return "Node [data=" + data + ", next=" + next + "]";
	}
	private String data;
	private Node next;
}

Output

Node [data=Vivek, next=Rochit] ==> Node [data=Rochit, next=Gyan] ==> Node [data=Gyan, next=Praveen] ==> Node [data=Praveen, next=null]

Related Article

Implement Custom Doubly Linked List in Java

Leave a Reply

Your email address will not be published. Required fields are marked *