C++结构体变量和指向结构体变量的指针构成链表 链表有一个头指针变量,以head表示,它存放一个地址,该地址指向一个元素。链表中的每个元素称为结点,每一个结点都应包括两个部分:
-
用户须要用的实际数据ios
-
下一个结点的地址。ide
经典案例:C++使用结构体变量。#include<iostream>//预处理 using namespace std;//命名空间 int main()//主函数 { struct Student{ //自定义结构体变量 int num;//学号 char sex;//性别 int age;//年龄 struct Student *next; }; Student stu1,stu2,stu3,*head,*point;//定义Student类型的变量stu stu1.num=1001;//赋值 stu1.sex='M';//赋值 stu1.age=18;//赋值 stu2.num=1002;//赋值 stu2.sex='M';//赋值 stu2.age=19;//赋值 stu3.num=1003;//赋值 stu3.sex='M';//赋值 stu3.age=20;//赋值 head=&stu1;//将结点stu1的起始地址赋给头指针head stu1.next=&stu2;//将结点stu2的起始地址赋给stu1结点的next成员 stu2.next=&stu3;//将结点stu3的起始地址赋给stu2结点的next成员 stu3.next=NULL;//结点的next成员不存放其余结点地址 point=head;//point指针指向stu1结点 do { cout<<point->num<<" "<<point->sex<<" "<<point->age<<endl; point=point->next;//使point指向下一个结点 }while(point!=NULL); return 0; //函数返回值为0; }编译运行结果:1001 M 18 1002 M 19 1003 M 20 -------------------------------- Process exited after 1.179 seconds with return value 0 请按任意键继续. . .