关于删除链表中结点
生成两个链表a,b,包括学号,姓名。将a中学号与b中重合的删除。我编了个程序,分为三部分,主函数int main(),生成函数creat(),删除函数delet(),输出函数print().
但执行时删除函数总是出错,找不到错在哪儿,希望指教。
#include<stdio.h>
#include<malloc.h>
#define N 5
struct student
{
int num;
char name[8];
struct student *next;
};
int main()
{
struct student *creat();
struct student *delet(struct student *p1,struct student *p2);
void print(struct student *p);
struct student *p1, *p2, *p3;
printf("please enter the first:\n");
p1 = creat();
printf("please enter the second:\n");
p2 = creat();
printf("The deleted:\n");
p3=delet(p1, p2);
print(p3);
return 0;
}
struct student *creat()
{
struct student *p1, *p2, *head;
int i = 1;
p1 = (struct student *)malloc(sizeof(struct student));
scanf("%d %s", &p1->num, p1->name);
head = p2 = p1;
while(i !=N)
{
p1 = (struct student *)malloc(sizeof(struct student));
scanf("%d %s", &p1->num, p1->name);
p2->next = p1;
p2 = p1;
i++;
}
p2->next = NULL;
return head;
}
struct student *delet(struct student *p1, struct student *p2)
{
struct student *st1, *st2, *temp;
st1 = p1;
st2 = p2;
while (st1!=NULL)
{
st2 = p2;
while ((st1->num != st2->num)&&(st2!=NULL))
{
st2 = st2->next;
}
if (st1->num == st2->num)
{
if (st1 == p1)
{
p1 = st1->next;
}
else
{
temp->next = st1->next;
st1 = st1->next;
}
}
else
{
temp = st1;
st1 = st1->next;
}
}
return p1;
}
void print(struct student *p)
{
while (p != NULL)
{
printf("%d %s\n", p->num, p->name);
p = p->next;
}
}