输出错乱问题未解决!!!!!
//9.9 写一函数建立一个有3名学生数据的单向动态链表。
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n;
struct Student * creat(void) //定义建立链表函数。返回一个指向链表头的指针(头指针)。
{
struct Student *head;
struct Student *p1, *p2;
n = 0;
p1 = p2 = (struct Student *)malloc(LEN); //开辟一个新单元。
scanf("%ld%f", &p1->num, &p1->score);
head = NULL;
while (p1->num != 0)
{
n = n + 1;
if (n == 1) //如果是第一个节点 将头指针head指向第一个节点
{
head = p1;
}
else //如果不是第一个节点则依次将上一个next指向下一个节点的起始位置。
{
p2->next = p1;
}
p2 = p1; //将p2指向p1,准备下次循环。
p1 = (struct Student*)malloc(LEN); //开辟新的节点。
scanf("%ld,%f", &p1->num, &p1->score);
}
p2->next = NULL;
return(head);
}
void print(struct Student *head) //链表输出函数。
{
struct Student * p;
printf("\n these %d record are:\n", n);
p = head;
if (head != NULL)
{
do
{
printf("%ld %5.2f\n", p->num, p->score);
p = p->next;
} while (p != NULL);
}
}
struct Student *del(struct Student *head, long num) //链表删除函数。
{
struct Student *p1, *p2;
if (head == NULL)
{
printf("list null!\n");
return(head);
}
p1 = head; //p1指向链表头
while ((num != p1->num)&&(p1->next != NULL))
{ //当p1不是所找的节点时,p2指向p1原来位置 将p1后移 接着找
p2= p1;
p1 = p1->next;
}
if (num == p1->num)
{
if (p1 == head)
head = p1->next;
else
p2->next = p1->next;
printf("delete :%ld\n", num);
}
else
printf("%ld dont be found!!!\n", num);
return(head);
}
//insert 函数
struct Student *insert(struct Student *head, struct Student *stud)
{ //stud为想要插入的学生信息的结构体地址
struct Student *p0, *p1, *p2;
p1 = head;
p0 = stud;
if (head == NULL)
{
head = p0; //如果表为空,直接将数据接入即可。
p0->next = NULL;
}
else //表不为空则依次对比查找插入位置。
{
while ((p0->num > p1->num)&&(p1->next != NULL))
{
p2 = p1; //应p2=p1先,使2,1始终指向相邻的两个节点,否则指向一个了。
p1 = p1->next;
}
if (p0->num<=p1->num)
{
if (head == p1) //如果
head = p0;
else
{
p2->next = p0;
p0->next = p1;
}
}
else
{
p1->next=p0;
p0->next = NULL;
}
}
n = n + 1;
return(head);
}
int main() //主函数
{
struct Student *pt; //声明建立链表函数。
void print(struct Student * head); //声明输出链表函数。
pt = creat();
printf("\n num:%d\n score:%f\n ", pt->num, pt->score);
print(pt);
return 0;
}