DEV Community

Cover image for Data Structure in Java: Linked List
luthfisauqi17
luthfisauqi17

Posted on • Edited on

4 2

Data Structure in Java: Linked List

public class LinkedList {
    class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    private Node head;
    LinkedList() {
        this.head = null;
    }
    LinkedList(int data) {
        this.head = new Node(data);
    }

    public void insertFront(int data) {
        if(this.head == null) this.head = new Node(data);
        else {
            Node temp = new Node(data);
            temp.next = this.head;
            this.head = temp;
        }
    }

    public void insertBack(int data) {
        if(this.head == null) this.head = new Node(data);
        else {
            Node temp = this.head;
            while(temp.next != null) temp = temp.next;
            temp.next = new Node(data);
        }
    }

    public int removeFront() {
        int data = this.head.data;
        Node temp = this.head;
        this.head = temp.next;
        temp = null;
        return data;
    }

    public int removeBack() {
        Node temp = this.head;
        while(temp.next.next != null) temp = temp.next;
        int data = temp.next.data;
        temp.next = null;
        return data;
    }

    public void show() {
        Node temp = this.head;
        while (temp != null) {
            System.out.printf("%d ", temp.data);
            temp = temp.next;
        }
        System.out.println();
    }
}
Enter fullscreen mode Exit fullscreen mode

Sources and Images:

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay