|
楼主 |
发表于 2011-9-19 12:53:48
|
显示全部楼层
好吧 沙发 自己占了
这个又加了一个循环插入的功能 但是 没有检查输入是否正确的问题:
代码:
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- struct student
- {
- long int num;
- long double score;
- struct student *next;
- };
- void main()
- {
- struct student *p1, *p2, *head, *p;
- int n;
- long int Temp_Num;
-
- n = 0;
- head = NULL;
- p1 = p2 = (struct student *)malloc(sizeof (struct student));
-
- printf ("input Num : ");
- scanf ("%ld", &p1->num);
- printf ("input Score : ");
- scanf ("%lf", &p1->score);
-
- while (p1->num)
- {
- n++;
- if (1 == n)
- {
- head = p1;
- }
- else
- {
- p2->next = p1;
- }
- p2 = p1;
- p1 = (struct student *)malloc(sizeof (struct student)); //开辟新节点 使p1指向这个节点.
-
- printf ("input Num : "); //读入一个num给p1所指的节点.
- scanf ("%ld", &p1->num);
- printf ("input Score : ");
- scanf ("%lf", &p1->score);
- }
-
- p2->next = NULL; //p2->next = NULL
- p = head;
- printf ("\ninput %ld number\n\n", n);
- printf ("Num\t\t\tScore\n");
- if (head)
- {
- do
- {
- printf ("%ld\t\t\t%3.2lf\n", p->num, p->score);
- }
- while (p = p->next);
- }
-
-
- p1 = head;
- p2 = head;
- p = (struct student *)malloc(sizeof (struct student));
- printf ("\n\nplease input insert Num: "); //按照(num)数字前后顺序插入节点
- scanf ("%ld", &p->num);
- printf ("please input insert score: ");
- scanf ("%lf", &p->score);
- while (1)
- {
- if (head == NULL) //如果是空链表的情况.
- {
- head = p;
- head->next = NULL;
- n++;
- }
- else
- {
- while (p->num > p1->num && p1->next != NULL)
- {
- p2 = p1;
- p1 = p1->next;
- }
- if (p->num >= p1->num && p1->next == NULL) //如果要插入的节点为最后面
- {
- p1->next = p;
- p->next = NULL;
- n++;
- } //如果要插入的节点为最后面
- else if (p->num <= p2->num && p2 == head) //如果要插入的节点排序为第一个
- {
- p->next = p1;
- head = p;
- n++;
- } //如果要插入的节点排序为第一个
-
- else if (p->num >= p2->num && p->num <= p1->num) //如果要插入的节点在链表中间
- {
- p2->next = p;
- p->next = p1;
- n++;
- } //如果要插入的节点在链表中间
- }
- p1 = head;
- printf ("\ninput %ld number\n\n", n);
- printf ("Num\t\t\tScore\n");
-
- if (head)
- {
- do
- {
- printf ("%ld\t\t\t%3.2lf\n", p1->num, p1->score);
- }
- while (p1 = p1->next);
- }
-
-
- //这里实现多次插入.
- printf ("如果要再一次插入请直接输入数据\n\n否则要退出请按数字 0 : ");
- p1 = head;
- p2 = head;
- p = (struct student *)malloc(sizeof (struct student));
- scanf ("%ld", &p->num);
- printf ("请输入相应的分数: ");
- scanf ("%lf", &p->score);
- if (0 == p->num)
- {
- printf ("\n退出\n");
- break;
- }
- }
- system("pause");
- }
复制代码
|
|