list 链表的 创建、输出(打印)、删除、插入 2011.07.26

来源:互联网 发布:nds经典游戏 知乎 编辑:程序博客网 时间:2024/06/04 18:33

老早就买了 谭浩强的C程序设计,就是那本绿皮的。

好久不看了,最近同学来借,觉得这本书回来的可能性就不大了,赶紧再翻翻。

还是把链表再写写吧,这是基础:


#include <iostream>using namespace std;#include <malloc.h>#define LEN sizeof(struct student)struct student{int num;float score;student * next;};int n;/************************************************************************//* create function                                                      *//************************************************************************/struct student * creat(){student * head, *p1, *p2;n = 0;p1 = p2 = (student *)malloc(LEN);cout<<"please input the num and the score:"<<endl;cin>>(p1->num)>>(p1->score);head = NULL;while (p1->num != 0){n = n+1;if (n == 1){head = p1;}else{p2->next = p1;}p2 = p1;p1 = (student *)malloc(LEN);cin>>(p1->num)>>(p1->score);}p2->next = NULL;return (head);}/************************************************************************//* print function                                                       *//************************************************************************/void print(student * head){student * p;cout<<"These "<<n<<" records are:"<<endl;p = head;if (head != NULL){while (p != NULL){cout<<(p->num)<<"\t"<<(p->score)<<endl;p = p->next;}}}/************************************************************************//* delete function                                                      *//************************************************************************/struct student * del(student * head, int num){student * p1, * p2;if (head == NULL){cout<<"list null!"<<endl;return NULL;}p1 = head;while (num != p1->num && p1->next != NULL){p2 = p1;p1 = p1->next;}if (num == p1->num){if (p1 == head){head = p1->next;}else{p2->next = p1->next;}cout<<"delete: "<<num<<endl;n = n - 1;}else{cout<<num<<" not been found!"<<endl;}return (head);}/************************************************************************//* insert function                                                      *//************************************************************************/struct student * insert(student * head, student * stud){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;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(){student *p;student  a;a.num = 5055;a.score = 66.66;p = creat();print(p);del(p, 1002);print(p);insert(p, &a);print(p);return 0;}

输出:

please input the num and the score:
1001 111
1002 222
1003 333
1004 444
1005 555
0
0
These 5 records are:
1001    111
1002    222
1003    333
1004    444
1005    555
delete: 1002
These 4 records are:
1001    111
1003    333
1004    444
1005    555
These 5 records are:
1001    111
1003    333
1004    444
1005    555
5055    66.66




原创粉丝点击