修复此LinkedList,不显示预期输出
我以为我的一切都正确了,但是当我编译程序时,输出不是我所期望的。我希望该程序显示“ 0 1 2 3 4 5”,但无济于事。如果有人可以帮助指出我的错误或修复程序,我真的很感激。 Thks
#include <iostream>
#include <fstream>
using namespace std;
struct Item {
int val;
Item* next;
};
void insert(Item *head, int value) {
Item *newnode = new Item;
newnode->val =value;
newnode->next = nullptr;
if (!head) {
head=newnode;
}
else {
Item *temp = head;
while (temp->next != nullptr)
temp=temp->next;
temp->next = newnode;
}
}
void display(Item *head) {
Item *temp = head;
while (temp) {
cout << temp->val << " " << endl;
temp = temp->next;
}
}
int main()
{
Item *head1=nullptr;
for(int k = 0; k < 6; k++)
insert(head1,k);
display(head1);
return 0;
}
I thought I had everything right but when I compile the program the output is not what I was expecting. I wanted the program to display "0 1 2 3 4 5" but to no avail. I did be grateful if someone can help point out my mistake or fix the program. Thks
#include <iostream>
#include <fstream>
using namespace std;
struct Item {
int val;
Item* next;
};
void insert(Item *head, int value) {
Item *newnode = new Item;
newnode->val =value;
newnode->next = nullptr;
if (!head) {
head=newnode;
}
else {
Item *temp = head;
while (temp->next != nullptr)
temp=temp->next;
temp->next = newnode;
}
}
void display(Item *head) {
Item *temp = head;
while (temp) {
cout << temp->val << " " << endl;
temp = temp->next;
}
}
int main()
{
Item *head1=nullptr;
for(int k = 0; k < 6; k++)
insert(head1,k);
display(head1);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的插入方法按值将
item *
进行,因此它不能在主函数中更改head
变量。因此,您正在一遍又一遍地使用nullptr
调用插入物,从不更改head
。如果您通过参考而传递,则代码有效:但是它不是很C ++ - ISH。 C ++具有构造函数和破坏者,使用它们。您的代码会泄漏内存,因为您永远不会释放列表。值得在容器
list
中划出功能,而不是直接使用item*
。而且,如果您跟踪列表的尾巴,那么末尾插入的速度要快得多,list
容器允许您轻松地做:Your insert method takes a
Item *
by value so it can not alter thehead
variable in the main function. So you are calling insert withnullptr
over and over and never changinghead
. If you pass by reference instead the code works:But it's not very C++-ish. C++ has constructors and destructors, use them. Your code leaks memory because you never free the list. It's worth it to capsulate functionality in a container
List
instead of using theItem*
directly. And if you keep track of the tail of the list then inserting at the end becomes much faster, which aList
container allows you to do easily: