[路飞]_每天刷leetcode_62( 设计链表 Design Linked List)

146 阅读4分钟

「这是我参与2022首次更文挑战的第23天,活动详情查看:2022首次更文挑战

设计链表 Design Linked List

LeetCode传送门707. 设计链表

题目

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
  • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
  • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
  • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
  • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。

Design your implementation of the linked list. You can choose to use a singly or 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 the MyLinkedList class:

  • MyLinkedList() Initializes the MyLinkedList object.
  • int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
  • void addAtHead(int 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.
  • void addAtTail(int val) Append a node of value val as the last element of the linked list.
  • void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
  • void deleteAtIndex(int index) Delete the indexth 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 myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2);    // linked list becomes 1->2->3
myLinkedList.get(1);              // return 2
myLinkedList.deleteAtIndex(1);    // now the linked list is 1->3
myLinkedList.get(1);              // return 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.

思考线


解题思路

在做这道题之前,我们要看清约束条件,在LeetCode中文版中写道- 所有 val值都在 [1, 1000] 之内。 这个约束条件是有问题的。根据测试用例和英文版描述,可以知道真正的范围在[0, 1000].

我们再来看一下我们要实现的内容。get\addHead\addTail\...等比较简单,我在这里主要说一下addAtIndex这个函数的实现思路。

这个函数要求,如果index < 0 我们就在头部插入。所以我们首先检测一下index和0的关系。

其次,由于我们要插入到index位置的前面,而我们在构建链表的时候插入了dummyHead正好能保证,如果我们的循环index--则得到的结果就是index前一个节点。同时我们要保证在循环的时候,链表一直是有值的,所以最后的约束条件为index-- && node. 在循环结束后若node不为空,说明存在节点。我们只要正常的执行插入就可以了。

addAtIndex代码如下

    addAtIndex(index: number, val: number): void {
        let node = this.dummyHead;
        if (index < 0) {
            this.addAtHead(val)
        }
        while (index-- && node) {
            node = node.next;
        }
        if (node) {
            const next = node.next;
            node.next = new LinkList(val, next);
        }
    }

而我们整体的代码如下:

class MyLinkedList {

    dummyHead: LinkList | null

    constructor() {
        this.dummyHead = new LinkList(-1, null);
    }

    get(index: number): number {
        let node = this.dummyHead.next;
        while (index-- && node) {
            node = node.next;
        }

        return node ? node.val : -1;
    }

    addAtHead(val: number): void {
        this.dummyHead.next = new LinkList(val, this.dummyHead.next);
    }

    addAtTail(val: number): void {
        let node = this.dummyHead;
        while (node.next) {
            node = node.next;
        }
        node.next = new LinkList(val, null)

    }

    addAtIndex(index: number, val: number): void {
        let node = this.dummyHead;
        if (index < 0) {
            this.addAtHead(val)
        }
        while (index-- && node) {
            node = node.next;
        }
        if (node) {
            const next = node.next;
            node.next = new LinkList(val, next);
        }
    }
    deleteAtIndex(index: number): void {
        let node = this.dummyHead;
        while (index-- && node) {
            node = node.next;
        }
        if (node) {
            const next = node.next;
            node.next = next?.next ?? null;
        }
    }
}
class LinkList {
    val: number
    next: LinkList | null
    constructor(val: number, next: LinkList | null) {
        this.val = val;
        this.next = next || null
    }
}

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

时间复杂度

addAtHead:O(1) addAtInder,O(K), K为 索引 Index. addAtTail:O(N), N 为链表的长度

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。