Implementation of LinkedList in java

 Linkedlist is a type of data structure which has nodes and pointers. Node a structure which stores data and pointers are used to link the nodes. To implement linkedlist in Java collections framework, we use doubly-linked list.

Doubly-linkedlist has two pointers. One points to forward direction and another points to backward direction.

Use of doubly-linkedlist:

  • It is dynamic. You can increase the size at runtime.
  •  Insertions and deletions are done in efficient manner.

Implementation of Linked List:

              This includes the creation of a linked list, adding the elements, displaying the elements, removing a data and iteration.

Steps:

Include the builtin java packages java.util.LinkedList and java.util.Iterator.

 A class “LinkedListSample” is created with main() function.

Creation of Linked list :

LinkedList is created as String with an object linkList.

Inserting the data:

Using add() function,data is added to linkList.

Display the data:

 It uses get() function to get the data and display using print statement.

Remove a data:

 It uses the remove() function.

Iteration:

              Using iterator, it creates an object. A function hasNext() helps for iteration.

Program:

import java.util.LinkedList;

import java.util.Iterator;

public class LinkedListSample {

    public static void main(String[] args) {

        LinkedList<String> linkList = new LinkedList<>();

        // insert the data to node

        linkList.add("alpha");

        linkList.add("beta");

        linkList.add("Gamma");

        linkList.addFirst("Head Node");

        linkList.addLast("Last Node");

        // LinkedList printing statement

        System.out.println("The LinkedList is displayed: " + linkList);

        // get the elements andd display it

        String Element1 = linkList.getFirst();

        String Elementn = linkList.getLast();

        String Element2 = linkList.get(1);

        System.out.println("First Element is: " + Element1);

        System.out.println("Last Elements is: " + Elementn);

        System.out.println("Second Element is: " +Element2);

        // delete the elements

        linkList.removeFirst();

        linkList.removeLast();

        linkList.remove(1);

        // tranverse in LinkedList

        System.out.println("The iterated list after the removal of data");

        Iterator<String> iterator1 = linkList.iterator();

        while (iterator1.hasNext()) {

            System.out.println(iterator1.next());

        }

    }

}

Output:

C:\raji\blog>javac LinkedListSample.java

C:\raji\blog>java LinkedListSample

The LinkedList is displayed: [Head Node, alpha, beta, Gamma, Last Node]

First Element is: Head Node

Last Elements is: Last Node

Second Element is: alpha

The iterated list after the removal of data

alpha

Gamma

This is the way of implementing Linked list in java. Enjoy Coding!!!

No comments:

Post a Comment