You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决链表相邻节点交换(swap pairs)函数的段错误问题?

问题分析与修复

核心错误点

  • 成员名误用:node类的存储数据的成员是data,但swap_pair函数中错误使用了value,这会导致编译错误或未定义行为。
  • 空指针访问:循环条件仅检查before != nullptr,当链表剩余节点数为1时,before->next为nullptr,此时访问after->data(原代码是after->value)以及后续的before->next->next都会触发段错误。

修复后的代码

#include<bits/stdc++.h>
using namespace std;
class node{
    public:
    int data;
    node *next;
    node(int d)
    {
        this->data=d;
        this->next=nullptr;
    }
};

class ll
{
    private:
    node *head=nullptr;
    node *tail=nullptr;
    public:
    void inserthead(int value)
    {
        node *newnode=new node(value);
        if(head==nullptr)
        {
            head=newnode;
            tail=newnode;
        }
        else{
            newnode->next=head;
            head=newnode;
        }
    }
    void inserttail(int value)
    {
        node *newnode=new node(value);
        if(tail==nullptr)
        {
            head=newnode;
            tail=newnode;
        }
        else{
            tail->next=newnode;
            tail=newnode;
        }
    }
    void print()
    {
        node *temp=head;
        while(temp!=nullptr)
        {
            cout<<temp->data<<" ";
            temp=temp->next;
        }
        cout<<endl;
    }
    void swap_pair()
    {
        node *before=head;
        // 循环条件需同时保证before和before->next都不为空
        while(before != nullptr && before->next != nullptr)
        {   
            node* after=before->next;
            // 修正成员名,使用data而非value
            int temp=before->data;
            before->data=after->data;
            after->data=temp;
            // 移动两步,此时before->next不为空,所以before->next->next不会访问空指针
            before=before->next->next;
        }
    }
};
int main()
{
    ll l1;
    l1.inserthead(2);
    l1.inserthead(1);
    l1.inserttail(3);
    l1.inserttail(4);
    l1.swap_pair();
    l1.print();
    return 0;
}

关键修改说明

  1. 修正成员访问:将before->value和after->value改为before->data和after->data,匹配node类的成员定义。
  2. 完善循环条件:将循环条件改为before != nullptr && before->next != nullptr,确保每次循环都有两个相邻节点可以交换,避免空指针访问。
  3. 优化输出格式:修改print函数的输出,让结果在一行显示为2 1 4 3,符合预期输出格式。

内容的提问来源于stack exchange,提问作者SAMRAT SARKAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 04:17:19