9.6 C++指向結構體變量的指針

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 請按任意鍵繼續. . .
相關文章
相關標籤/搜索