链表是一种重要的数据结构,今天我们来简单学习一下。
链表:由一系列节点组成,每个节点由一个数据域和一个指针域组成。
超简单的一个静态链表:
#include<stdio.h>
struct people
{
int age;
struct people *next;
}
int main()
{
struct people a,b,c,*head,*p;//定义结构体变量和结构体指针
a.age=1;
b.age=2;
c.age=3;
head=&a;//头指针指向第一个节点的地址
a.next=&b;
b.next=&c;
c.next=NULL;
p=head;
while(p!=NULL)
{
printf("%d\n",p->age);
p=p->next;//节点移动
}
return 0;
}
打印结果:1 2 3
建立动态链表:每个节点用连个指针来进行处理
谭老师一个例子:
#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,已经循环过一次,则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;
}
程序目的是输出第一个节点的值。其中在create中处理相对复杂,下面来看一个简单一点的create函数:
struct student *createList()
{
struct student *p1,*p2,*head;
p1=p2=head=(struct student *)malloc(sizeof(struct student));//head一开始就有指向,省去 了head=NULL工作,后面也不需要对head进行判断
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;
}
我觉得这个函数比上面代码简洁一些。
本文讲了静态链表和动态链表的实现方法。