Skip to main content

Command Palette

Search for a command to run...

code in java

Updated
•2 min read•View as Markdown

\


public class problems {
    public static void main(String[] args) {
        LinkedList list = new LinkedList(); 

        int[] values = {1, 2, 3, 4, 5}; // Hardcoded input
        for (int val : values) {
            list.addToTheLast(new Node(val));
        }

        list.printList();

        list.addFirst(new Node(0));
        list.printList();

        list.removeFirst();
        list.printList();

        list.removeLast();
        list.printList();

        list.addAtIndex(new Node(10), 2);
        list.printList();

        list.removeAtIndex(2);
        list.printList();
    }
}

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

class LinkedList {
    Node head;  

    public void addToTheLast(Node node) {
        if (head == null) {
            head = node;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }

    public void addFirst(Node node) {
        node.next = head;
        head = node;
    }

    public void removeFirst() {
        if (head != null) {
            head = head.next;
        }


    }

    public void removeLast() {
        if (head == null || head.next == null) {
            head = null;
            return;
        }
        Node temp = head;
        while (temp.next.next != null) {
            temp = temp.next;
        }
        temp.next = null;
    }

    public void addAtIndex(Node node, int index) {

    }

    public void removeAtIndex(int index) {
        if (head == null) return;
        if (index == 0) {
            removeFirst();
            return;
        }
        Node temp = head;
        for (int i = 0; temp != null && i < index - 1; i++) {
            temp = temp.next;
        }
        if (temp == null || temp.next == null) return;
        temp.next = temp.next.next;
    }

    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }  
        System.out.println();
    }
}

More from this blog

codebhghvhv

34 posts