通过含有一个自身结构的指针,我们可以实现随机分布的结构变量的遍历,链表的组成是一个个链接的结点,每个结点是同类型的结构变量,可以通过程序的方法来建立和显示链表,可插入、删除、增加结点来维护一个链表。一个链表总是含有链首指针。
#include<iostream>
#include<iomanip>
using namespace std;
struct Student{
long number;
float score;
Student * next;
};
Student * head;
Student * getNode(){
int num;
float sc;
cin>>num>>sc;
if(num==0)
return NULL;
Student * p=new Student;
p->number=num;
p->score=sc;
p->next=0;
return p;
}
void Create(){
if((head=getNode())==0)
return;
for(Student * pE=head,*pS;pS=getNode();pE=pS)
pE->next=pS;
}
void ShowList(){
cout<<"now the items of list are\n";
for(Student * p=head;p;p=p->next)
cout<<p->number<<","<<p->score<<endl;
}
int main(){
cout<<fixed<<setprecision(1);
Create();
ShowList();
}
在主函数中,先调用Create函数,从无到有创建一个链表。然后调用ShowList函数,输出整个链表。全局指针head是链首指针,它在各种链表操作(插入、删除、输出)中,作为关键而又公共的数据被大家取用。ShowList()是输出链表,它取得链首指针head,输出链表每个结点。它需要定义另一个p指针,从head开始,遍历链表结点。显然,不能用head指针去遍历结点,以防止链表首地址丢失。
在Create()函数中,首先调用getNode函数,新建一个结点给head指针。函数getNode如果返回NULL,表示后面再无新结点。所以Head自然只能获得NULL的值。如果getNode函数返回从堆中申请到的结点地址,则说明已建新结点,循环插入链尾,直到再无结点。Create函数结束后,head指针则指向一个由堆中申请的各个结点链接而成的链首。