【发布时间】:2021-06-06 02:24:44
【问题描述】:
我用 C++ 编写了一个链接列表插入程序。当我添加一个函数来在链表的最后一个位置插入一个节点时,我得到了一个奇怪的输出。似乎正在输出地址。这是我的代码。
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d)
{
data=d;
}
};
class operations
{
public:
Node *head;
Node *ptr;
void insertfirst(int d)
{
Node *newnode = new Node(d);
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
}
else
{
newnode->next=head;
head=newnode;
}
}
void display()
{
Node *ptr;
ptr=head;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->next;
}
}
void insertafter(int key, int d)
{
Node *ptr;
ptr=head;
while(ptr->data!=key)
{
if(ptr->next==NULL)
{
cout<<"Key not found";
return;
}
ptr=ptr->next;
}
Node *newnode=new Node(d);
newnode->next=ptr->next;
ptr->next=newnode;
}
void insertlast(int d)
{
Node *ptr;
ptr=head;
Node *newnode = new Node(d);
newnode->next=NULL;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=newnode;
}
};
int main()
{
operations o;
o.insertfirst(4);
o.insertfirst(3);
o.insertafter(3,5);
o.insertlast(1);
o.display();
return 0;
}
我得到的输出是:
3 5 4 1577825 1
我的预期输出是:
3 5 4 1
我应该怎么做才能获得预期的输出?
【问题讨论】:
-
如果目标是链表,为什么类叫操作?这与 DSA 有什么关系?
-
提供的代码对我来说只是因分段错误而崩溃。
-
如果首先调用
insertlast(),请确保您正确处理head节点(提示,您确实需要一个初始化head = nullptr;的operations的构造函数,并且您需要检查@987654328 是否@ 在您尝试通过访问->next指针来取消引用head之前。如果添加tail指针,您将避免在insertlast()中进行迭代。
标签: c++ algorithm pointers data-structures dsa