为什么insert插入结点,插入在头结点位置会有问题?求解:
/*****************************************/
/***********简单的数据链表程序************/
/*****************************************/
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#define LEA sizeof(struct student)
struct student
{
int num;
float score;
struct student *next;
};
struct student *expror(); //创建链表;
void print(struct student *head); //打印链表;
struct student *del(struct student *head, int num); //删除结点;
struct student *insert(struct student *head, struct student *p); //插入结点;
void main()
{
struct student *p, *p1, *Max;
int n = 0;
p = expror();
print(p);
printf("Please input Number delete: ");
scanf("%d", &n);
print(del(p, n));
p1 = (struct student *)malloc(LEA);
printf("Please input Number insert: ");
scanf("%d", &p1->num);
printf("Please input Score insert: ");
scanf("%f", &p1->score);
Max = insert(p, p1);
print(Max);
getch();
}
struct student *expror()
{
struct student *p1, *p2, *head;
int n = 0;
head = NULL;
p1 = p2 = (struct student *)malloc(LEA);
printf("Please input Number: ");
scanf("%d", &p1->num);
printf("Please input Score: ");
scanf("%f", &p1->score);
while(p1->num)
{
n++;
if(1 == n)
{
head = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
p1 = (struct student *)malloc(LEA);
printf("Please input Number: ");
scanf("%d", &p1->num);
printf("Please input Score: ");
scanf("%f", &p1->score);
}
p2->next = NULL;
return head;
}
void print(struct student *head)
{
while(head != NULL)
{
printf("Number = %d\t\tScore = %f\n", head->num, head->score);
head = head->next;
}
}
struct student *del(struct student *head, int num)
{
struct student *p1, *p2;
p1 = head;
if(head == NULL)
{
printf("Fuck you!!!");
}
else
{
while(p1->next != NULL && p1->num != num)
{
p2 = p1;
p1 = p1->next;
}
if(p1->num == num)
{
if(head == p1)
{
head = p1->next;
}
else
{
p2->next = p1->next;
}
}
}
return head;
}
struct student *insert(struct student *head, struct student *p)
{
struct student *p0, *p1, *p2;
p1 = head;
p0 = p;
if(head == NULL)
{
printf("Fuck you!!!");
}
else
{
while(p0->num > p1->num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if(p0->num < p1->num)
{
if(head == p1)
{
head = p0;
p0->next = p1;
}
else
{
p2->next = p0;
p0->next = p1;
}
}
else
{
p1->next = p0;
p0->next = NULL;
}
}
return head;
}
|