Linked List

by Aryan Katiyar
0 comment 257 views

In this article you’ll learn about linked list and how to make a linked list program in java.

What is Linked List?

Linked list is a linear collection of objects called nodes. Each node contains a data field to store the content and a pointer to hold the reference to the next node. In linked list, every node is connected to its neighbour node by storing the address of the next node.

There is a head pointer, which points to the first node and the last node contains null.

Overview:

Linked List
Linked list illustration

How to a Create a node in linked list

In order to make linked list , we have to create a node class first. In Java we don’t have pointers, so we have to use references to point to the next node.

class node // creating a node class for storing data { int data; //can be of any datatype node next; //must of type class }
Code language: JavaScript (javascript)
Linked List

Creating the main class

import java.util.Scanner; public class linkedlist { static node head = null; public static void main(String args[]) { insert_and_display obj = new insert_and_display() ; Scanner sc = new Scanner(System.in); System.out.println("Enter number of values you want to insert"); int input = sc.nextInt(); System.out.println("Enter values to insert in the linked list"); for(int i =1;i<=input;i++) { int value = sc.nextInt(); obj.insert(value); //calling the insert function } System.out.println("Displaying......"); obj.display(); //calling the display function } }
Code language: JavaScript (javascript)

Creating an insert and display function in linked list

class insert_and_display { void insert(int value ) { node nnode = new node(); //creating a new node nnode.next=null; //initializing next variable to null nnode.data = value; if(linkedlist.head==null) //for newly created linked list { linkedlist.head = nnode; } else { node temp= linkedlist.head; node temp2=null; for(;temp!=null;temp=temp.next) //iterating to get the end node for insertion of new node { temp2 = temp; } temp2.next=nnode; } } void display() // to print all the node values { node temp =linkedlist.head; for( ;temp!=null; temp=temp.next) { System.out.println(temp.data); } } }
Code language: JavaScript (javascript)

In order to insert a node in a linked list , we have to create a insert() method where we check whether the linked list already exists or not. If linked list already exists then the new node is added to the end of the last node, otherwise a new linked list is created.

To display the values stored in a linked list , display( ) method is created. Using the linked list head we have to find the first node, then print the values one by one until null is encountered.

Click here , to read my previous article on java arrays.

You may also like