# 707.Design-Linked-List

## 707. Design Linked List

## 题目地址

<https://leetcode.com/problems/design-linked-list/>

## 题目描述

```
Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.

Implement these functions in your linked list class:

get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1.
addAtHead(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.
addAtTail(val) : Append a node of value val to the last element of the linked list.
addAtIndex(index, 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.
deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid.


Example:

Input: 
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[1],[1]]
Output:  
[null,null,null,null,2,null,3]

Explanation:
MyLinkedList linkedList = new MyLinkedList(); // Initialize empty LinkedList
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1, 2);  // linked list becomes 1->2->3
linkedList.get(1);            // returns 2
linkedList.deleteAtIndex(1);  // now the linked list is 1->3
linkedList.get(1);            // returns 3


Constraints:

0 <= index,val <= 1000
Please do not use the built-in LinkedList library.
At most 2000 calls will be made to get, addAtHead, addAtTail,  addAtIndex and deleteAtIndex.
```

## 代码

### Approach #1 Singly Linked List

**Complexity Analysis**

* Time complexity: O(1) for addAtHead. O(*k*) for get, addAtIndex, and deleteAtIndex, where k is an index of the element to get, add or delete. O(*N*) for addAtTail.
* Space complexity: O(1) for all operations.

```java
class ListNode {
  int val;
  ListNode next;
  ListNode(int x) {val = x;};
}

class MyLinkedList {
    int size;
  ListNode head;
  /** Initialize your data structure here. */
  public MyLinkedList() {
        size = 0;
    head = new ListNode(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 < 0 || index >= size)        return -1;
    ListNode curr = head;
    for (int i = 0; i < index + 1; i++) {
      curr = curr.next;
    }
    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;

    if (index < 0)    return 0;

    size++;
    ListNode pred = head;
    for (int i = 0; i < index; i++) {
      pred = pred.next;
    }

    ListNode toAdd = new ListNode(val);
    toAdd.next = pred.next;
    pred.next = toAdd;
  }

  /** Delete the index-th node in the linked list, if the index is valid. */
  public void deleteAtIndex(int index) {
        if (index < 0 || index >= size)        return;
    size--;
    ListNode pred = head;
    for (int i = 0; i < index; i++) {
      pred = pred.next;
    }

    pred.next = pred.next.next;
  }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */
```

### Approach #2 Doubly Linked List

**Complexity Analysis**

* Time complexity: O(1) for addAtHead and addAtTail. O(min(*k*,*N*−*k*)) for get, addAtIndex, and deleteAtIndex, where k*k* is an index of the element to get, add or delete.
* Space complexity: O(1) for all operations.

```java
class ListNode {
  int val;
  ListNode next;
  ListNode prev;
  ListNode(int x) { val = x; }
}

class MyLinkedList {
  int size;
  ListNode head, tail;
  public MyLinkedList() {
    size = 0;
    head = new ListNode(0);
    tail = new ListNode(0);
    head.next = tail;
    tail.prev = head;
  }

  public int get(int index) {
    if (index < 0 || index >= size)        return -1;

    ListNode curr = head;
    if (index + 1 < size - index) {
      for (int i = 0; i< index + 1; i++) {
        curr = curr.next;
      }
    } else {
      curr = tail;
      for (int i = 0; i < size - index; i++) {
        curr = curr.prev;
      }
    }

    return curr.val;
  }

  public void addAtHead(int val) {
    ListNode pred = head, succ = head.next;
    size++;

    ListNode toAdd = new ListNode(val);
    toAdd.prev = pred;
    toAdd.next = succ;
    pred.next = toAdd;
    succ.prev = toAdd;
  }

  public void addAtTail(int val) {
    ListNode succ = tail, pred = tail.prev;

    size++;
    ListNode toAdd = new ListNode(val);
    toAdd.prev = pred;
    toAdd.next = succ;
    pred.next = toAdd;
    succ.prev = toAdd;
  }

  public void addAtIndex(int index, int val) {
    if (index > size)        return;
    if (index < 0)        index = 0;

    ListNode pred, succ;
    if (index < size - index) {
      pred = head;
      for (int i = 0; i < index; i++) {
        pred = pred.next;
      }
      succ = pred.next;
    } else {
      succ = tail;
      for (int i = 0; i < size - index; i++) {
        succ = succ.prev;
      }
    }

    size++;
    ListNode toAdd = new ListNode(val);
    toAdd.prev = pred;
    toAdd.next = succ;
    pred.next = toAdd;
    succ.prev = toAdd;
  }

  public void deleteAtIndex(int index) {
    if (index < 0 || index >= size)        return;

    ListNode pred, succ;
    if (index < size - index) {
      pred = head;
      for (int i = 0; i < index; i++) {
        pred = pred.next;
      }
      succ = pred.next.next;
    } else {
      succ = tail;
      for (int i = 0; i < size - index - 1; i++) {
        succ = succ.prev;
      }
      pred = succ.prev.prev;
    }

    size--;
    pred.next = succ;
    succ.prev = pred;
  }

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/data-structure/707.design-linked-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
