虽然数组可以实现连续存储,但是由于数组每次定义时,都必须给出长度,使用不是很灵活,容易造成资源浪费,链表可以实现动态定义,利用malloc()函数可以申请动态空间的特性,使用该函数,需要添加stdlib.h头文件;
#include <stdio.h>
#include <stdlib.h>
struct linked_list //声明结构体,里面存储节点数据即下一个节点的地址;
{
int date;
struct linked_list *next; //定义指针变量,存储下一个节点地址
};
int main(void)
{
int i,n,a; //n为节点个数
struct linked_list *p,*q,*t,*head; //t用作遍历链表,head指向链表的第一个节点,称作头指针
p=q=t=head=NULL; //开始时将他们指向NULL
scanf("%d",&n);
for(i=0;i<n;++i)
{
scanf("%d",&a);
p=(struct linked_list *)malloc(sizeof(struct linked_list)); //申请动态空间,并用p指向它
p->date=a; //可以向该节点输入数据
p->next=NULL; //先将next指向NULL
if(head==NULL) //头指针指向NULL说明是第一个节点
head=p; //将头指针指向第一个节点
else
q->next=p;
q=p; //用q指向p指向的节点,因为下一次执行循环时,p要
指向下一个节点
}
//遍历链表
t=head; //将t指向第一个节点
while(t->next!=NULL)
{
printf("%d ",t->date);
t=t->next; //t指向下一个节点
}
return 0;
}