如何解决数据为字符串的C语言链表实现
我是数据结构的新手,通过 udemy 和在线课程学习,最近我写了一个链表来删除一个数据为 int 的特定节点,但后来当我使用数据作为字符串实现它时,我不断收到分段错误。请检查并让我知道我需要如何继续...
#include <stdio.h>
#include<stdlib.h>
struct Node
{
char *data;
struct Node* next;
};
int main()
{
int n;
int i;
char *temp;
char* string;
struct Node* start;
struct Node *newNode1;
start = (struct Node*)malloc(sizeof(struct Node));
printf("Enter the number of the nodes::\n");
scanf("%d",&n);
printf("Enter the strings inside each Node:\n");
scanf("%s",temp);
//First node must be a point to start variable
struct Node* temp1,*temp2;
temp1=start;
temp1->data = temp;
for(i=2;i<=n;++i)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
scanf("%s",temp);
newNode->data = temp;
temp1->next = newNode;
temp1=temp1->next;
temp1=start;
}
printf("Enter the specific Node you wanted to delete:\n");
scanf("%s",temp);
while(temp1->next!=NULL)
{
if(temp1->data==temp)
{
break;
}
else
{
temp2=temp1;
temp1=temp1->next;
}
}
temp2->next = temp1->next;
printf("Now the temp2 and temp1 values are %p and %p",temp1,temp2);
free(temp1);
/*display*/
printf("The elements are:\n");
temp1 =(struct Node*) malloc(sizeof(struct Node));
temp1=start;
while(temp1->next!=NULL)
{
printf("%s->",temp1->data);
temp1=temp1->next;
}
printf("%s->NULL",temp1->data);
return 0;
}
如果有人能解释为什么我会出现分段错误,以及我如何解决这个错误,以便得到一个链接列表作为马铃薯->tamato->brinjal->apple->grape 作为输出。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。