In the previous post, Representation of Singly Linked List in Java,we learned How Custom Linked List represented internally.
In this post, We will learn How to insert a node at the beginning of a 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
Singly LinkedList
Inserting a Node at the beginning of a Singly Linked List:
Case 1: If Linked List is empty Then adding newNode at the beginning:
Case 2:If Linked List is not empty Then adding newNode at the beginning:
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 46 47 48 49 50 51 52 53 |
package com.kkjavatutorials.util; /** * How to insert a node at the beginning of a Singly Linked List in Java? * @author KK JavaTutorials */ public class LinkedList<T> { private Node<T> head; private static class Node<T>{ private T data; private Node<T> next; public Node(T data) { super(); this.data = data; this.next = null; } } /** * This method insert a Node at the beginning of the List * @param data has to insert in the List */ public void insertFirst(T data) { Node<T> newNode = new Node<T>(data); newNode.next = head; head = newNode; } /** * Method which traverse Linked List and display all data. */ public void displayLinkedList() { Node<T> currentNode = head; while(currentNode!= null) { System.out.print(currentNode.data+"->"); currentNode = currentNode.next; } System.out.println(currentNode); } public static void main(String[] args) { LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.insertFirst(10); linkedList.insertFirst(20); linkedList.displayLinkedList(); } } |
Output of this Program:
20->10->null
You May Also Like:
- 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
That’s all about the How to Insert node at the end of a Singly Linked List in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.