初识链表
鏈表是一種重要的數(shù)據(jù)結(jié)構(gòu),今天我們來簡單學(xué)習(xí)一下。
鏈表:由一系列節(jié)點(diǎn)組成,每個節(jié)點(diǎn)由一個數(shù)據(jù)域和一個指針域組成。
?
超簡單的一個靜態(tài)鏈表:
?
#include<stdio.h>struct people {int age;struct people *next; }int main() {struct people a,b,c,*head,*p;//定義結(jié)構(gòu)體變量和結(jié)構(gòu)體指針a.age=1;b.age=2;c.age=3;head=&a;//頭指針指向第一個節(jié)點(diǎn)的地址a.next=&b;b.next=&c;c.next=NULL;p=head;while(p!=NULL){printf("%d\n",p->age);p=p->next;//節(jié)點(diǎn)移動}return 0; }打印結(jié)果:1 2 3
?
建立動態(tài)鏈表:每個節(jié)點(diǎn)用連個指針來進(jìn)行處理
譚老師一個例子:
?
#include<stdio.h> #include<stdlib.h>struct student {int age;struct student *next; };strcut student *createList() {int n=0;struct student *p1,*p2,*head;p1=p2=(struct student *)malloc(sizeof(struct student));scanf("%d",&p1->age);//這是是取地址head=NULL;//head置為NULL,等會還會處理while(p1->age!=0){n=n+1;if(n==1)head=p1;//開始n=1,已經(jīng)循環(huán)過一次,則p1也被重新分配過else p2->next=p1;p2=p1;p1=(struct student *)mallo(sizeof(struct student));scanf("%d",&p1->age);}p2->next=NULL;//必要的return head; }int main() {struct student *p;p=createList();printf("%d",pt->age);retrun 0; }程序目的是輸出第一個節(jié)點(diǎn)的值。其中在create中處理相對復(fù)雜,下面來看一個簡單一點(diǎn)的create函數(shù):
struct student *createList() {struct student *p1,*p2,*head;p1=p2=head=(struct student *)malloc(sizeof(struct student));//head一開始就有指向,省去 了head=NULL工作,后面也不需要對head進(jìn)行判斷scanf("%d",&p1->age);while(p1->age!=0){p1=(struct student *)malloc(sizeof(struct student));p2->next=p1;p2=p1;scanf("%d",&p1->age);} p2->next=NULL;return head; }我覺得這個函數(shù)比上面代碼簡潔一些。
?
?
本文講了靜態(tài)鏈表和動態(tài)鏈表的實(shí)現(xiàn)方法。
?
?
?
?
?
?
總結(jié)
- 上一篇: 学结构体了
- 下一篇: 一个程序看fputc和fgetc