Push 发表于 2012-2-21 14:35:41

链表问题

为什么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;
}

wangyexin 发表于 2012-2-21 14:35:42

插到头结点后 你要把头结点改为新结点

三天一打进北大 发表于 2012-2-22 19:04:04

非常有问题。。。。

___光 发表于 2012-2-22 19:37:40

student里的num是指的什么?

2004wmj 发表于 2014-9-8 11:36:32

谢谢分享,非常喜欢!

2002wmj 发表于 2014-9-21 22:50:01

写的很不错,谢谢分享

错过会难过 发表于 2014-9-21 23:03:01

代码好乱...

错过会难过 发表于 2014-9-21 23:07:21

代码加点注释啦,:mad:

恋色天空 发表于 2014-9-22 16:37:55

把错误信息贴出来看看吧
页: [1]
查看完整版本: 链表问题