我在Dev C++中做一个单链表的C程序,代码如下:
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *insert(node*,int,int);
node *create(int);
node *del(node*,int);
int print(node*);
int main()
{
node *head;
int n,ch,n1,x,key,k;
head = NULL;
printf("\n Number of nodes:");
scanf("%d",&n);
while(1)
{
printf("\nYour choices are:");
printf("\n1) Create");
printf("\n2) Print");
printf("\n3) Insert");
printf("\n4) Delete");
printf("\n5) Reverse\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
head = create(n);
break;
case 2:
n1 = print(head);
break;
case 3:
printf("Enter the element to be inserted:");
scanf("%d",&x);
printf("Enter the position where it is to be inserted:");
scanf("%d",&key);
head = insert(head,x,key);
break;
case 4:
printf("Enter the element to be deleted:");
scanf("%d",&k);
head = del(head,k);
break;
case 5:
break;
default:
exit(0);
break;
}
}
return(0);
}
node *create(int n)
{
node *head,*p;
int i;
printf("Enter %d data fields",n);
head = (node*)malloc(sizeof(node));
head->next = NULL;
scanf("%d",&(head->data));
p=head;
for(i=1;i<n;i++)
{
p->next = (node*)malloc(sizeof(node));
p=p->next;
scanf("%d",&(p->data));
p->next=NULL;
}
printf("Linked list created.");
return(head);
}
int print(node *p)
{
while(p!=NULL)
{
printf("%d-->",p->data);
p=p->next;
}
printf("NULL");
return(0);
}
node *insert(node *head,int x,int key)
{
node *p,*q;
p = (node*)malloc(sizeof(node));
p->data = x;
if(key==-1)
{
p->next = head;
head=p;
}
else
{
q = head;
while(key != q ->data && q!=NULL)
q=q->next;
if(q!=NULL)
{
p->next = q->next;
q->next = p;
}
}
printf("Element Inserted.");
return(head);
}
node *del(node *head,int x)
{
node *p,*q;
if(x == head->data)
{
p = head;
head = head->next;
free(p);
}
else
{
while(x != (p->next)->data && p->next != NULL)
p=p->next;
if(p->next != NULL)
{
q = p->next;
p->next = (p->next)->next;
free(q);
}
}
return(head);
}
一切顺利,但是当我尝试删除一个节点时,控制台只是崩溃了,当我调试它时它显示“访问冲突错误:分段错误”我的程序有什么问题。