因此,我试图自己找出链表程序出问题的地方。头以某种方式得到更新。我知道这是一个小错误,但是我只是找不到我要去哪里。它与变量的全局声明有关吗?
#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;
}
}