LinkedList Data Structure in Java | PLM Developer

Linked List is a linear data structure. The elements in Linked List are not in sequence but, the sequence of nodes. Each node is connected to another node using pointers. These pointers refer to the next node in the list.

LinkedList In Java
LinkedList In Java

Types of Linked Lists:

  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List

Singly LinkedList with Insertion Operations:

public class LinkedList {
    Node head;

    class Node {
        int data;
        Node next;

        Node(int d) {
            data = d;
            next = null;
        }
    }

    //push operation - adding an element at first position
    void push(int new_value) {

        Node new_node = new Node(new_value);

        new_node.next = head;

        head = new_node;
    }


    //append operation - adding element at lastion position
    void append (int new_value) {

        Node new_node = new Node(new_value);

        if(head == null) {

            head = new Node(new_value);

            return;

        }

        new_node.next = null;

        Node last = head;

        while(last.next != null) {

            last = last.next;
        }

        last.next = new_node;
    }


    void insertAfter(Node prev_node, int new_value) {

        if(prev_node.next == null) {

            System.out.println("Insert After operation cannot be performed");

            return;

        }

        Node new_node = new Node(new_value);

        new_node.next = prev_node.next;

        prev_node.next = new_node;

    }


    //printing elements in lnked list
    void printNode() {

        Node last = head;

        while(last != null) {

            System.out.println(last.data+" ");

            last = last.next;
        }
    }

    public static void main(String[] args) {
        LinkedList llist = new LinkedList();

        llist.push(2);
        llist.push(4);
        llist.push(6);
        llist.push(8);
        llist.append(12);

        System.out.println("Head value: "+llist.head.data);

        llist.insertAfter(llist.head.next, 33);

        llist.printNode();
    }
}

output:
8 6 33 4 2 12

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top