> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/data-structures/linked-list.md).

# 链表

### 什么是链表

链表由一系列**结点**组成，每个结点存放数据和指向下一个结点的指针。与数组不同，链表的内存**不连续**，便于插入和删除。

### 结点定义

```cpp
struct Node {
    int val;
    Node *next;
    Node(int v) : val(v), next(nullptr) {}
};
```

### 头插法建表

```cpp
Node* head = nullptr;
for (int i = 1; i <= n; i++) {
    Node *p = new Node(i);
    p->next = head;
    head = p;
}   // 结果逆序：n ... 1
```

### 尾插法建表

```cpp
Node *head = nullptr, *tail = nullptr;
for (int i = 1; i <= n; i++) {
    Node *p = new Node(i);
    if (!head) head = tail = p;
    else { tail->next = p; tail = p; }
}   // 顺序：1 ... n
```

### 遍历

```cpp
for (Node *p = head; p; p = p->next)
    cout << p->val << " ";
```

### 插入（在 p 之后插入 x）

```cpp
Node *q = new Node(x);
q->next = p->next;
p->next = q;
```

### 删除（删除 p 的后继）

```cpp
Node *q = p->next;
p->next = q->next;
delete q;
```

### 反转链表

```cpp
Node* reverse(Node *head) {
    Node *prev = nullptr;
    while (head) {
        Node *nxt = head->next;
        head->next = prev;
        prev = head;
        head = nxt;
    }
    return prev;
}
```

### 单链表 / 双链表 / 循环链表

| 类型   | 特点                  |
| ---- | ------------------- |
| 单链表  | 每个结点一个 next 指针      |
| 双链表  | 有 prev 和 next，可双向遍历 |
| 循环链表 | 尾结点的 next 指回头结点     |

> 链表插入 / 删除是 O(1)（已知位置时），但随机访问是 O(n)。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/data-structures/linked-list.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
