代码随想录之链表

79 阅读2分钟

链表理论基础

  1. 链表的定义
struct ListNode {
    int val;
    ListNode *next;
    ListNode(): val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
}
  1. 如何回收内存?
struct ListNode *node = new ListNode();
delete node;

虚拟头节点-203 (re-test)

Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return *the new head*.

要点:

  1. 可以尝试虚拟头节点,方便处理更新头节点的情况

错误:

  1. 回收链表节点内存的时机,避免use after free

链表常见操作-707 (re-test)

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.

要点:

  1. 内部变量用下划线开头。

错误:

  1. this是指针
  2. 增加 删减元素需要改变count值
  3. 注意头节点的处理

反转链表-206 (re-test)

Given the `head` of a singly linked list, reverse the list, and return *the reversed list*.

要点:

  1. 双指针法

错误:

  1. 注意边界条件
  2. 注意避免形成环

删除倒数第n个节点-19

Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.

要点:

  1. 双指针法

错误:

  1. 注意审题,注意nth node的含义

环形链表-142

Given the `head` of a linked list, return *the node where the cycle begins. If there is no cycle, return* `null`.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.

**Do not modify** the linked list.

要点:

  1. 如何判断是否有环 双指针法,如果相遇,则有环
  2. 寻找环的入口 相遇节点与头节点同时出发,相遇的地方就是入口节点。
  3. 必须要一个一步 一个两步