Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.2 kB
3
Indexable
Never
public class Test {
    public static void main(String[] args) {
        SinglyLinkedList list = new SinglyLinkedList(); // {null}
        list.insertToHead(5); // {5} -> {null}
        list.insertToTail(1); // {5} -> {1} -> {null}
        list.insertToHead(2); // {2} -> {5} -> {1} -> {null}
        list.insertToTail(3); // {2} -> {5} -> {1} -> {3} -> {null}

        list.traverse();
    }
}

class SinglyLinkedList {
    Node head;

    void insertToHead(int value) {
        Node newNode = new Node();
        newNode.data = value;
        newNode.next = head;
        head = newNode;
    }

    void insertToTail(int value) {
        Node newNode = new Node();
        newNode.data = value;

        if (head == null){
            head = newNode;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = newNode;
        }        
    }

    void traverse() {
        Node temp = head;
        while (temp != null) {
            System.out.println(temp.data);
            temp = temp.next;
        }
    }
}

class Node {
    int data;
    Node next;
}