Linked List Implementation In Java
Chapter:
Data Structures
Last Updated:
09-03-2018 16:48:13 UTC
Program:
/* ............... START ............... */
class Node {
public int data;
public Node next;
public void displayNode() {
System.out.println("{ " + data + " } ");
}
}
public class SinglyLinkedList {
private Node first;
private Node last;
public SinglyLinkedList() {
}
public boolean isEmpty() {
return (first == null);
}
// used to insert at the beginning of the list
public void insertFirst(int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = first;
first = newNode;
}
public Node deleteFirst() {
Node temp = first;
first = first.next;
return temp;
}
public void displayList() {
System.out.println("List (first --> last) ");
Node current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public void insertLast(int data) {
Node current = first;
while (current.next != null) {
current = current.next; // we'll loop until current.next is null
}
Node newNode = new Node();
newNode.data = data;
current.next = newNode;
}
public static void main(String[] args) {
SinglyLinkedList mylist = new SinglyLinkedList();
mylist.insertFirst(100);
mylist.insertFirst(50);
mylist.insertFirst(99);
mylist.insertFirst(88);
mylist.insertLast(9999999);
mylist.displayList();
}
}
/* ............... END ............... */
Output
List (first --> last)
{ 88 }
{ 99 }
{ 50 }
{ 100 }
{ 9999999 }
Notes:
-
We can assume java linked list structure as a train with bogie and each bogie is connected. For each bogie we can call it as Node in Java. Each node has a data element and pointer to the next element. Variable data stores the value of the element and next stores the reference to the next node.
- In the above program please go the Node class with data and next reference variable for better understanding about Node creation.
- SinglyLinkedList mylist = new SinglyLinkedList() will create a linkedlist with empty reference of first and last.
- isEmpty() will check whether linkedlist is empty or not (If first == null list will be empty).
- insertFirst(int data) using the insertFirst function we can insert data in the front of linkedlist. For inserting data first we create a new node and initialize data value and reference to the new node will the next first.
- insertLast(int data) like wise insert in front insertlast will insert data at the last of linkedlist. First we will create a new node and data variable fill with a value, and point the last current node next value to the reference of new node created.
- In singly linkedlist nodes are connected to its immediate next node with reference variable (Node next). If the last node links to null, it shows that the list is empty. For this kind of list Only one-way traversal is possible.
Tags
Linkedlist Implementation, Java linkedlist,singly linkedlist, Data Structures