【发布时间】: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中的附加逻辑。分配n时temp的值是多少? -
????????,谢谢,评论很有帮助。
标签: c++ algorithm data-structures linked-list singly-linked-list