【发布时间】:2017-09-27 14:23:09
【问题描述】:
我目前正在编写一个程序,该程序实现了一个链表来维护一个按排序顺序排列的整数列表。程序从文件中读取整数,格式为
d [\t] 7
i [\t] 8
i [\t] 7
i [\t] 10
'd' 表示从列表中删除,'i' 插入到列表中,不允许重复整数。这是我到目前为止的代码:
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
int delete(struct Node** head, int key){
if(head == NULL)
{
return -1;
}
struct Node* ptr = *head;
struct Node* prev = NULL;
while(ptr->data != key && ptr->next!=NULL)
{
prev = ptr;
ptr = ptr->next;
}
if(ptr->data == key)
{
if(prev)
{
prev->next = ptr->next;
}
else
{
*head = ptr->next;
}
free(ptr);
return key;
}
return -1;
}
int insert(struct Node** head, struct Node* newNode){
struct Node* ptr;
if(*head == NULL || (*head)->data >= newNode->data)
{
newNode->next = *head;
*head = newNode;
}
else
{
ptr = *head;
while(ptr->next != NULL && ptr->next->data < newNode->data)
{
ptr = ptr->next;
}
newNode->next = ptr->next;
ptr->next = newNode;
}
return 0;
}
int main(int argc, char* argv[]){
FILE *fp = fopen(argv[1], "r");
int num, found;
char c;
struct Node* head = NULL;
struct Node* ptr = head;
while(fscanf(fp, "%c\t%d\n", &c, &num)!=EOF)
{
for(ptr=head; ptr!=NULL; ptr=ptr->next)
{
if(ptr->data == num)
{
found = 1;
}
}
if(found != 1)
{
if(c == 'i')
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = num;
newNode->next = NULL;
insert(&head, newNode);
}
}
if(c == 'd')
delete(&head, num);
}
found = 0;
}
for(ptr=head; ptr!=NULL; ptr=ptr->next)
{
printf("%d ", ptr->data);
}
return 0;
}
当第一个字母是 'i' 时它工作正常,但每当第一个字母是 'd' 时,我就会遇到分段错误。这是为什么呢?
【问题讨论】:
-
可能不是问题,但你需要初始化一些东西,尤其是
found -
您可能想阅读以下内容:How to debug small programs
-
如果key不在列表中,当在while循环检查中ptr等于tail时,在while循环体中ptr = ptr->next将导致ptr为NULL,并在下一次迭代中, ptr->data 将导致分段错误,因为您将尝试取消对 NULL 指针的引用。
-
while(ptr-....-ptr可能为空!
标签: c linked-list segmentation-fault