我一直试图弄清楚我在这个链表程序中做错了什么

I have been trying to figure out what I am doing wrong in this linked list program

本文关键字:程序 什么 错了 链表 一直 弄清楚      更新时间:2023-10-16

所以我试图自己找出我的链表程序出错的地方。 头部以某种方式更新。我知道这是一个很小的错误,但我只是没有找到我出错的地方。它与变量的全局声明有关吗?

#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++概念(,正如有人在评论中指出的那样,您应该坚持使用一个(除非您正在学习编程课程并且您的教授希望您使用某些方法(。