【问题标题】:error in swapping two lines in insert last function of linked list在插入链表的最后一个函数中交换两行时出错
【发布时间】:2015-10-29 12:14:36
【问题描述】:

我不明白单链表中插入最后一个函数的一件事。这个函数总是在最后一个节点之后插入新项目。

newNode->next=temp->next;
temp->next=newNode;

我遇到了一个错误。我不知道为什么?请帮忙!!

int insertLast(int item)
{

    struct listNode *newNode,*temp;
    newNode=(struct listNode*)malloc(sizeof(struct listNode));

    newNode->item=item;
    newNode->next=NULL;
    if(list==NULL)
    {
        list=newNode;
    }
    else
    {
        temp=list;
        while(temp->next!=NULL)temp=temp->next;
        newNode->next=temp->next;
        temp->next=newNode;
    }
    return SUCCESS_VALUE;
}

【问题讨论】:

  • 什么错误? newNode 和 temp 是如何定义的?
  • 已编辑!请检查代码!谢谢!
  • 您具体遇到了什么错误?我假设列表是列表头部的名称,它的范围是什么?我们仍然需要更多信息
  • 交换提到的 2 行是否有错误?第一行什么也没做,也没用。
  • 不完全是错误!运行代码后它停止工作! :( yap 1st 2 行是那些正在被交换的行,然后代码没有运行说停止工作..

标签: c++ linked-list


【解决方案1】:
newNode->next=temp->next;

NewNode->next 应该保留null,因为您要添加到列表的末尾。现在你的列表最后会有一个圆圈(temp->newNode->temp->newNode...),所以你将无法通过它。

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多