在c++中创建链表
Creation of linked list in c++
我试图通过这个代码实现链表…我认为第一个节点被创建,它的数据,但指针指向下一个节点是不工作的第二次它说分割故障…请帮助
#include<cstdio>
#include<cstdlib>
struct node {
int data;
struct node *next;
};
struct node *root;
void append(int num)
{
struct node *conductor;
if (root == NULL) {
root = new node;
root->data = num;
root->next = NULL;
conductor = conductor->next;
} else {
conductor = root;
while (conductor != NULL)
conductor = conductor->next;
conductor->next = new node;
conductor = conductor->next;
conductor->next = NULL;
conductor->data = num;
}
}
void display()
{
struct node *conductor;
conductor = root;
while (conductor->next != NULL) {
printf("%d->", conductor->data);
conductor = conductor->next;
}
printf("%d->", conductor->data);
}
int main()
{
int choice, num;
while (1) {
printf("Enter the choicen");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &num);
append(num);
break;
case 2:
display();
break;
case 3:
exit(0);
}
}
return (0);
}
正确代码:
#include<cstdio>
#include<cstdlib>
struct node {
int data;
struct node *next;
};
struct node *root;
void append(int num)
{
struct node *conductor;
if (root == NULL) {
root = new node;
root->data = num;
root->next = NULL;
// conductor = conductor->next; This was not needed at all.
} else {
conductor = root;
while (conductor->next != NULL) // You were doing conductor != NULL
conductor = conductor->next;
conductor->next = new node;
conductor = conductor->next;
conductor->next = NULL;
conductor->data = num;
}
}
void display()
{
struct node *conductor;
conductor = root;
if (conductor == NULL) return; // Returning if root is NULL
while (conductor->next != NULL) {
printf("%d->", conductor->data);
conductor = conductor->next;
}
printf("%dn", conductor->data);
}
int main()
{
int choice, num;
while (1) {
printf("Enter the choicen");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &num);
append(num);
break;
case 2:
display();
break;
case 3:
exit(0);
}
}
return (0);
}
相关文章:
- 使用std::list创建循环链表
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 在C++中为链表类创建实例
- C++ 双向链表:使用矩阵类成员创建和填充列表
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 无法创建或返回反向链表
- 在 C++ 中创建单个链表
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 程序在为链表创建推送函数时崩溃
- 自定义链表创建 RtlValidateHeap 错误,其结构具有链表
- 为数据缺少默认构造函数的链表创建节点
- 如何为链表C++创建"弹出尾巴"函数
- 如何为双链表创建交换函数
- 在链表创建循环中插入
- 正在为链表c++创建DataType
- 为链表C++创建节点
- 如何使用swap函数为双重链表创建冒泡排序
- 如何为链表创建复制构造函数