在C中为链接列表写了这个程序。我尝试在链表的末尾插入作为分段错误时插入错误。所有其他情况都在起作用,例如最初插入,插入2个元素之间等。花了很多时间思考,但无法弄清楚?
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void insert();
void display();
void search();
void delete();
struct node{
int val;
struct node *next;
}*head;
int num,count=0;
void main()
{
char dec = 'E';
printf("Welcome to the Linked List C Program!\n");
head = NULL;
while(1){
printf("Make a Choice:\n");
printf("I.Insert\nD.Delete\nS.Search\nd.Display\nE.Exit\n");
scanf(" %c",&dec);
switch(dec){
case 'I':
insert();
break;
case 'D':
delete();
break;
case 'S':
search();
break;
case 'd':
display();
break;
case 'E':
exit(0);
break;
default:
printf("Wrong input Try Again!\n");
}
}
}
void insert(){
printf("Enter the number to insert:");
scanf("%d",&num);
struct node *temp;
struct node *newnode;
struct node *prev;
int c =0;
//temp = (struct node *)malloc(sizeof(struct node));
newnode = (struct node *)malloc(sizeof(struct node));
//prev = (struct node *)malloc(sizeof(struct node));
newnode->val = num;
if(head==NULL)
{
head = newnode;
head->next = NULL;
}
else
{
temp = head;
//searching whether linked list is in start or end
while(temp->val<num && temp !=NULL)
{
printf("Index:%d Value:%d Address:%p",c,temp->val,temp);
prev = temp;
temp = temp->next;
c++;
printf("TEST\n");
}
if(c==0)
{
head = newnode;
head->next = temp;
}
else
{
prev->next=newnode;
newnode->next=temp;
}
}
}
void display()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d",temp->val);
temp = temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
void search()
{
printf("Enter the number tosearch for:\n");
scanf("%d",&num);
struct node *temp;
temp=head;
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
c++;
}
else if(temp == NULL)
{
printf("Not present!");
}
else
c++;
temp =temp->next;
}
}
void delete()
{
struct node *temp;
struct node *prev;
temp = head;
printf("Enter the value to delete:\n");
scanf("%d",&num);
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
printf("Deleting this element");
prev->next=temp->next;
free(temp);
c++;
}
else
c++;
prev = temp;
temp =temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
答案 0 :(得分:6)
在你的while循环中,你在检查temp
不是NULL之前检查temp
个成员之一:
while(temp->val<num && temp !=NULL)
反过来说:
while ((temp != NULL) && (temp->val < num))