Linked List 链表

Definition 链表定义

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

test_node = ListNode(0)
// 单链表
struct ListNode {
    int val;  // 节点上存储的元素
    ListNode *next;  // 指向下一个节点的指针
    ListNode(int x) : val(x), next(NULL) {}  // 节点的构造函数
};

ListNode* head = new ListNode(5);
class ListNode {
  val;
  next = null;
  constructor(value) {
    this.val = value;
    this.next = null;
  }
}

注意空指针

基础操作

添加节点

链表-添加节点

# 单链表插入 prev(C) new(F) C -> F -> D
new.next = prev.next # F->D
prev.next = new # C->F
# 双向链表插入 
new.next = a.next 
new.prev = b.prev
a.next = new
b.prev = new

删除节点

链表-删除节点

时间复杂度

进阶技巧

Dummy Node 哑巴/虚拟节点

翻转链表

# store cur node and prev node during iteration
tmp = c_node.next
c_node.next = p_node
p_node = c_node
c_node = tmp # c_node = c_node.next

合并有序链表

链表双指针