就只有删除头结点有问题啊, 郁闷的.帮我看一下.
struct node *Del(struct node *head,int date){ struct node *p1,*p2;
if(head==NULL)
{
printf("空表"); return head;
}
else
{
p1=head;
while(p1!=NULL&&p1->date!=date)
{
p2=p1; p1=p1->next;
}
if(p1==NULL)
{
printf("未找到%d\n",date); return head;
}
else if (p1==head)
{
head=p1->next; free(p1); return head;
}
else if (p1->next!=NULL)
{
p2->next=p1->next; free(p1); return head;
}
else
{
p2->next=NULL; free(p1); return head;
}
}
}
这是删除单向链表结点的函数, 删除中间和尾部结点都没有问题, 就删除头结点时出问题. 帮我看看有哪里不对的.
下面是整个程序
struct node
{ int date;
struct node *next;
};
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node *Del(struct node *head,int date);
struct node *Clist1(struct node *);
void Display(struct node *);
void main()
{ int date;
struct node *head1=NULL;
head1=Clist1(head1);
Display(head1);
printf("输入删除数据\n");
scanf("%d",&date);
Del(head1,date);
Display(head1);
}
/*建立链表函数*/
struct node *Clist1(struct node *head)
{ struct node *p,*p1; int n;
scanf("%d",&n);
/*开辟内存空间*/
p=(struct node *)malloc(sizeof(struct node));
p->date=n;p->next=NULL;
/*将head 和 p1 指向 p*/
head=p;p1=p;
scanf("%d",&n);
while(n!=0)/*以0结束*/
{ /*开辟内存空间*/
p=(struct node *)malloc(sizeof(struct node));
p->date=n;p->next=NULL;
p1->next=p;p1=p1->next;
scanf("%d",&n);
}
return head;
}
/*输出链表函数*/
void Display(struct node *head)
{ struct node *p;
p=head;
while(p!=NULL)
{ printf("[%d]-->",p->date);
p=p->next;
}
printf("NULL \n");
}
struct node *Del(struct node *head,int date)
{ struct node *p1,*p2;
if(head==NULL)
{
printf("空表"); return head;
}
else
{
p1=head;
while(p1!=NULL&&p1->date!=date)
{
p2=p1; p1=p1->next;
}
if(p1==NULL)
{
printf("未找到%d\n",date); return head;
}
else if (p1==head)
{
head=p1->next; free(p1); return head;
}
else if (p1->next!=NULL)
{
p2->next=p1->next; free(p1); return head;
}
else
{
p2->next=NULL; free(p1); return head;
}
}
}