1 条题解

  • 0
    @ 2026-8-19 9:50:30

    题解

    使用三个指针:

    pre:已经反转好的前半部分
    cur:当前结点
    nxt:暂存原来的下一个结点
    

    每轮:

    nxt = cur->next;
    cur->next = pre;
    pre = cur;
    cur = nxt;
    

    最后 pre 就是新的头结点。

    #include <bits/stdc++.h>
    using namespace std;
    
    struct Node {
        long long data;
        Node* next;
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int n;
        cin >> n;
    
        Node* head=nullptr;
        Node* tail=nullptr;
    
        for (int i=0;i<n;++i) {
            long long x; cin >> x;
            Node* node=new Node{x,nullptr};
            if (!head) head=tail=node;
            else {
                tail->next=node;
                tail=node;
            }
        }
    
        Node* pre=nullptr;
        Node* cur=head;
    
        while (cur) {
            Node* nxt=cur->next;
            cur->next=pre;
            pre=cur;
            cur=nxt;
        }
    
        head=pre;
    
        bool first=true;
        for (Node* p=head;p;p=p->next) {
            if (!first) cout << ' ';
            first=false;
            cout << p->data;
        }
        cout << '\n';
    
        while (head) {
            Node* t=head;
            head=head->next;
            delete t;
        }
        return 0;
    }
    

    时间复杂度 O(n)O(n),额外指针空间 O(1)O(1)(不计算链表本身)。

    • 1

    信息

    ID
    5149
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者