【问题标题】:logical error in singly linked list code c++单链表代码c ++中的逻辑错误
【发布时间】:2022-01-10 08:35:38
【问题描述】:

对于下面的代码,我想要的结果是4-->5-->,但是输出的结果只有4-->

对于上下文,我正在尝试仅在 c++ 中使用结构和函数来实现单链表。

代码:

#include <iostream>
using namespace std;
struct node
{
    int data;
    node* next;
};
node* head = NULL;
void insert(int val)
{

    node* n = new node();
    n->data = val;


    if(head == NULL)
    {
        head = n;
    }
    else
    {
        node* temp = head;
        while(temp!=NULL)
        {
            temp = temp->next;
        }
        temp = n;
    }
}
void display()
{
    if(head == NULL)
    {
        cout<<"UNDERFLOW ! LINKED LIST IS EMPTY !"<<endl;
    }
    else
    {
        cout<<"LINKED LIST!"<<endl;
        node* temp = head;
        while(temp!=NULL)
        {
            cout<<temp->data<<"-->";
            temp = temp->next;
        }
        cout<<endl;
    }
}
int main()
{
    insert(4);
    insert(5);
    display();
    return 0;
}

【问题讨论】:

  • 仔细查看insert 中的附加逻辑。分配ntemp的值是多少?
  • ????????,谢谢,评论很有帮助。

标签: c++ algorithm data-structures linked-list singly-linked-list


【解决方案1】:

正如@StephenNewell 正确指出的那样,插入函数中有一个错误。

同样在 C++ 中,使用 nullptr 而不是 NULL

insert()中更改以下代码:

node* temp = head;
while(temp!=NULL)
{
    temp = temp->next;
}
temp = n;

到:

node* temp = head;
while (temp->next != nullptr)
{
    temp = temp->next;
}
temp->next = n;

【讨论】:

  • 真的很有帮助,谢谢?。
  • @jdsingh,如果我的回答有帮助,请考虑投票:-)
【解决方案2】:

你的问题是temp是一个临时变量,你只是每次改变临时变量的值而不是链表的最后一个节点。

如果要改变指针的值,需要指针的指针或 你应该改成

while(temp->next != NULL)
{
    temp = temp->next;
}
temp->next = n;

【讨论】:

  • 非常感谢您帮助我?。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
相关资源
最近更新 更多