例建立链表,用链表存放学生数据表中每一个数据 项存放一个学生的数据。 链表建立程序如下: t include iostream. h tt define null o class student publIC char name [20] /*姓名*/ char id[10] /米学号米/ int score /*成绩米 student米next; /*指针米/ student ** head. *know. * last 2021/224
2021/2/24 6 链表建立程序如下: # include < iostream.h > # define NULL 0 class student { public: char name[20]; /* 姓名 */ char id[10]; /* 学号 */ int score; /* 成绩 */ student *next; /* 指针 */ }; student *head,*now,*last; 例 建立链表,用链表存放学生数据,表中每一个数据 项存放一个学生的数据
maint ( int head s last= NUll for(i=0;;i++) know new student 分配节点存储空间* if(noW==NULL)/判断自由空间是否够用 {cout≤≤“ In Not enough memory! exit(1) 空间不够,返回 cout<<“ In enter name:” cin>>now→name;/输入姓名至当前结点* if(now->name[o]==°0°) break; 2021/224
2021/2/24 7 main() { int i ; head = last = NULL ; for ( i=0 ; ; i ++ ) {now = new student ; /*分配节 点存储空间*/ if ( now == NULL ) /* 判断自由空间是否够用 */ { cout<< “ \n Not enough memory!”; exit(1) ; /* 空间不够,返回 */ } cout<< “ \n enter name: ” ; cin>>now -> name ; /* 输入姓名至当前结点 */ if ( now-> name[0] == ‘\0' ) break ;
else cout<"Ⅶ n enter id:"; cin>>now ->id /*输入学号至当前接点*/ cout< n enter score cin>now-> score;/*输入成绩至当前接点*/ now -> next NULL if ( head *判断是否第一节点head=NUL米/ head=now;/*头指针指向第一节点*/ else last->next=now;/*新节点添加在最后米/ last≡now; }/米 for end*/ 链表的建立有链表尾与插表头两种方式,上面程序使用的 是链表尾的方式 2021/224
2021/2/24 8 else {cout<<"\n enter id:" ; cin>>now -> id ; /* 输入学号至当前接点 */ cout<<"\n enter score"; cin>>now -> score ; /* 输入成绩至当前接点 */ now -> next = NULL ; if ( ! head ) /* 判断是否第一节点head=NULL*/ head = now ; /* 头指针指向第一节点 */ else last->next=now ; /* 新节点添加在最后 */ last=now; } } /* for end */ } 链表的建立有链表尾与插表头两种方式,上面程序使用的 是链表尾的方式