gpt4 book ai didi

c - 循环链表在列表开头添加节点时出现段错误 11

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:12 25 4
gpt4 key购买 nike

最初创建程序时,我可以创建仅添加第一个初始节点的循环链表。

一旦我尝试在开头添加新节点,它就会给我一个 Segmentation Fault 11。

我什至尝试在 Stack Overflow 中搜索这个问题,但他们中的许多人只是取消引用了指针变量。

#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *next;
};

struct node *start=NULL;
struct node *create_cll(struct node *);
struct node *display(struct node *);
struct node *add_beg(struct node *);
struct node *add_end(struct node *);
struct node *del_beg(struct node *);
struct node *del_end(struct node *);
struct node *del_aftgiven(struct node *);
struct node *del_entire(struct node *);

int main()
{
int option;
do
{
printf("\n\n****MAIN MENU****");
printf("\n\nEnter an option from the list given below");
printf("\n1. Create a linked list");
printf("\n2. Display the linked list");
printf("\n3. Add a node at the beginning of the list");
printf("\n4. Add a node at the end of the list");
printf("\n5. Delete a node from the beginning of the list");
printf("\n6. Delete a node from the ending of the list");
printf("\n7. Delete a node after a given node");
printf("\n8. Delete the entire linked list");
printf("\n");
scanf("%d",&option);

switch(option)
{
case 1: start = create_cll(start);
printf("\nCircular linked list created!");
break;

case 2: start = display(start);
break;

case 3: start = add_beg(start);
break;

}
}while(option!=4);
return 0;
}

struct node *create_cll(struct node *start)
{
struct node *new_node,*ptr;
int num;
printf("\nEnter -1 to stop adding new nodes");
printf("\nEnter the data:");
scanf("%d",&num);
if(num!=-1)
{
new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=num;
if(start!=NULL)
{
while(ptr->next!=start)
{
ptr=ptr->next;
}
ptr->next=new_node;
new_node->next=start;
}
else
{
new_node->next=new_node;
start=new_node;
}
}
return start;
}

struct node *display(struct node *start)
{
struct node *ptr;
ptr=start;
while(ptr->next!=start)
{
printf("\t %d",ptr->data);
ptr=ptr->next;
}
printf("\t %d",ptr->data);
return start;
}

struct node *add_beg(struct node *start)
{
struct node *ptr,*new_node;
int num;
printf("\nEnter the data you want to enter at the beginning:");
scanf("%d",&num);
new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=num;
if(ptr->next!=start)
{
ptr=ptr->next;
}
ptr->next=new_node;
new_node->next=start;
start=new_node;
printf("Node succesfully added:");
return start;
}

最佳答案

ptr

while(ptr->next!=start)

未赋值,使用->会报错。尝试将 ptr = start 放在它之前的行中。这也将发生在 add_beg() 中。

关于c - 循环链表在列表开头添加节点时出现段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53615388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com