我一直试图弄清楚我在这个链表程序中做错了什么
I have been trying to figure out what I am doing wrong in this linked list program
所以我试图自己找出我的链表程序出错的地方。 头部以某种方式更新。我知道这是一个很小的错误,但我只是没有找到我出错的地方。它与变量的全局声明有关吗?
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
}* head = NULL;
void insert()
{
struct node *newnode, *temp;
temp = (struct node*)malloc(sizeof(struct node));
newnode = (struct node*)malloc(sizeof(struct node));
cout << "Enter the element in the Linked list" << endl;
cin >> newnode->data;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
temp = head;
}
else {
temp->next = newnode;
temp = newnode;
}
}
void display(struct node* p)
{
while (p != NULL) {
cout << " " << p->data << endl;
p = p->next;
}
}
int main()
{
int ch;
do {
cout << "1.To Enter element in the Linked List" << endl;
cout << "2.To DIsplay Element in the Linked List" << endl;
cout << "3.To exit" << endl;
cin >> ch;
switch (ch) {
case 1: {
insert();
break;
}
case 2: {
display(head);
break;
}
}
} while (ch != 3);
return 0;
}
这里有一些问题,但最大的问题是你没有附加到链表的末尾。您需要查找列表中某个项目的->next
节点NULL
的位置,指示最终项目。然后,您的新节点应成为该项目的->next
节点。另外,请注意检查head
是否NULL
,在这种情况下,您的新节点应该变得head
。您可以修改insert()
函数以使其正常工作。
void insert()
{
struct node *newnode, *temp;
newnode = (struct node*)malloc(sizeof(struct node));
cout << "Enter the element in the Linked list" << endl;
cin >> newnode->data;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newnode;
}
}
注意:您混合了 C 和 C++ 的元素(malloc
是动态内存分配的 C 概念,而new
是一个C++概念(,正如有人在评论中指出的那样,您应该坚持使用一个(除非您正在学习编程课程并且您的教授希望您使用某些方法(。
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 正在解码MSVC 32位版本的程序集(作业).没有手术做什么
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- C++std::atomic在程序员级别保证了什么
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 什么是"undetectable means",它们如何更改 C/C++ 程序的对象?
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 使用动态链接加载程序 <dlfcn.h> 而不是直接函数调用的目的是什么?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我的堆栈和库存清单程序的结构有什么问题?
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- 没有信号处理程序的POSIX定时器的目的是什么?
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 指针和程序性能之间有什么关系吗?
- 我的C++级数计算程序出了什么问题?被困了好几个星期
- 是什么原因导致我的SDL2程序中出现杂散像素
- 程序什么时候会创建多个堆
- 为什么我的 espeak-ng 程序什么也没说?
- 为什么当打印BST的预购遍历时,我的程序什么都不做
- 我的c++程序什么也不做