Tuesday, October 2, 2018

707. Design Linked List






 95.67 %
class MyLinkedList {
    class Node {
        int val;
        Node prev;
        Node next;
        public Node(int val) {
            this.val = val;
        }
    }
    private Node head;
    private Node tail;
    private int size;
    /** Initialize your data structure here. */
    public MyLinkedList() {
        this.head = new Node(0);
        this.tail = new Node(0);
        head.next = tail;
        tail.prev = head;
        this.size = 0;
    }
   
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    public int get(int index) {
        if (index >= this.size) {
            return -1;
        }
        Node curr = head;
        while (index >= 0) {
            curr = curr.next;
            index--;
        }
        return curr.val;
    }
   
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    public void addAtHead(int val) {
        addAtIndex(0, val);
    }
   
    /** Append a node of value val to the last element of the linked list. */
    public void addAtTail(int val) {
        addAtIndex(size, val);
    }
   
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        // index = 1
        Node prevNode = head;
        while (index > 0) {
            prevNode = prevNode.next;
            index--;
        }
        Node nextNode = prevNode.next;
        Node curr = new Node(val);
        prevNode.next = curr;
        curr.prev = prevNode;
        curr.next = nextNode;
        nextNode.prev = curr;
        size++;
    }
   
    /** Delete the index-th node in the linked list, if the index is valid. */
    public void deleteAtIndex(int index) {
        if (index >= size) {
            return;
        }
        Node prevNode = head;
        while (index > 0) {
            prevNode = prevNode.next;
            index--;
        }
        Node nextNode = prevNode.next.next;
        prevNode.next = nextNode;
        nextNode.prev = prevNode;
        size--;
    }
}

No comments:

Post a Comment