简单链表操作

来源:互联网 发布:mac word转pdf 白边 编辑:程序博客网 时间:2024/06/05 00:50

新建控制台应用程序,然后添加如下代码

#include <iostream.h>struct tSTUDENT{char name[20];bool sex;int  number;int score;tSTUDENT* next;};tSTUDENT* g_pFirst = NULL;void ListInit(){}void ListDestroy(){tSTUDENT* p = NULL;tSTUDENT* q = NULL;if(g_pFirst){p = g_pFirst;while(p){q = p->next;delete p;p = q;}g_pFirst = NULL;}}void ListClear(){tSTUDENT* p = NULL;tSTUDENT* q = NULL;if(g_pFirst){p = g_pFirst;while(p){q = p->next;delete p;p = q;}g_pFirst = NULL;}}int ListLength(){int count = 0;tSTUDENT* p = NULL;tSTUDENT* q = NULL;if(g_pFirst){p = g_pFirst;while(p){count++;q = p->next;p = q;}}return count;}tSTUDENT*  GetElem(int num){tSTUDENT* p = NULL;tSTUDENT* q = NULL;if(g_pFirst){p = g_pFirst;while(p){if(num == p->number){return p;}q = p->next;p = q;}}return NULL;}void ListInsert(char* pName,bool sex,int number,int score){tSTUDENT* p = NULL;tSTUDENT* q = NULL;tSTUDENT* r = NULL;p = new tSTUDENT;for(int i=0;i<20;i++){p->name[i] = pName[i];}p->sex = sex;p->number = number;p->score = score;p->next = NULL;if(g_pFirst){q = g_pFirst;while(q->next){q = q->next;}q->next = p;}else{g_pFirst = p;}}void ListDelete(int num){tSTUDENT* p = NULL;tSTUDENT* q = NULL;if(g_pFirst){p = g_pFirst;if(num == p->number){g_pFirst = p->next;delete p;return;}else{while(p){if(p->next){if(num == p->next->number){q = p->next;p->next = q->next;delete q;return;}}p = p->next;}}}}void ListVisit(){tSTUDENT* p = NULL;tSTUDENT* q = NULL;if(g_pFirst){p = g_pFirst;while(p){cout<<"Name :"<< p->name<<endl;cout<<"sex "<<p->sex<<endl;cout<<"Number :"<<p->number<<endl;cout<<"score:"<<p->score<<endl;cout<<"---------------"<<endl;q = p->next;p = q;}}}void main(){char name[20];int sex;int  score;int  num;cout<<"please input students' information ..."<<endl;for(int i=0;i<3;i++){cout<<"Input the name:";cin>>name;cout<<"Input the sex:";cin>>sex;cout<<"Input the score:";cin>>score;cout<<"Input the number:";cin>>num;ListInsert(name,bool(sex),num,score);}ListVisit();ListDestroy();}


运行效果如下


0 0
原创粉丝点击