文章

116

粉丝

133

获赞

206

访问

70.0k

头像
反转链表 题解:
P565
发布于 2026年11月
阅读数 41

思路

迭代法(推荐):三个指针 pre(已反转部分的头)、cur(当前待处理节点)、nxt(cur 的后继)。

每一步的顺序不能错:

nxt = cur->next;   // 先把后继存下来,否则一改指针就丢了
cur->next = pre;   // 当前节点指向前驱
pre = cur;         // 前驱后移
cur = nxt;         // 当前后移

循环结束时 cur 为 NULL,pre 就是新头。

递归法:reverse(head->next) 先把后面整条链反转好,再让 head->next->next = head; head->next = NULL;。思路优雅,但递归深度等于链表长度,n = 10^5 时会爆栈,评测机上不可靠,因此标程用迭代。

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

参考代码(C++,ACM 模式)

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int val;
    Node *next;
    Node(int v) : val(v), next(NULL) {}
};

int main() {
    int n;
    if (!(cin >> n)) return 0;

    Node dummy(0);
    Node *t = &dummy;
    for (int i = 0; i < n; i++) {
        int x; cin >> x;
        t->next = new Node(x); t = t->next;
    }
    Node *head = dummy.next;

    // 迭代反转
    Node *pre = NULL, *cur = head;
    while (cur) {
        Node *nxt ...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发