In this post, I will talk about the Representation of Singly Linked List in Java?
Singly LinkedList is a Data Structure used to store the collection of nodes and having the following properties:
- It has a sequence of nodes.
- Every Node has two parts, the first part is data, and the second part is the reference to the next node in the List.
- First Node is called head Node.
- Last node always point to NULL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.kkjavatutorials.util; /** * Singly LinkedList generic class * @author KK JavaTutorials */ public class LinkedList<T> { //This class Represent Node in Singly LinkedList private static class Node<T>{ private T data; private Node<T> next; public Node(T data) { super(); this.data = data; this.next = null; } } public static void main(String[] args) { //Let's say I would like to create below Singly LinkedList Representation //10->20->30->40->50->null Node<Integer> head = new Node<Integer>(10); Node<Integer> secondNode = new Node<Integer>(20); Node<Integer> thirdNode = new Node<Integer>(30); Node<Integer> fourthNode = new Node<Integer>(40); Node<Integer> fifthNode = new Node<Integer>(50); head.next = secondNode; secondNode.next = thirdNode; thirdNode.next = fourthNode; fourthNode.next = fifthNode; Node<Integer> currentNode = head; while (currentNode != null) { System.out.print(currentNode.data+" "); currentNode = currentNode.next; System.out.println(currentNode); } } } |
Output of this Program:
10 [email protected]
20 [email protected]
30 [email protected]
40 [email protected]
50 null
This output shows that the last node is pointing to a null reference
You May Also Like:
- How to check whether a linked list has a loop/cycle in java ?
- Queue Implementation using LinkedList in java
- Queue Implementation using an array in java
- Queue Data Structure
- How to Implement Stack in java using Linked List ?
- Stack implementation in Java using array
- Java Program to find the frequency of each character in String ?
That’s all about the Representation of Singly Linked List in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.