链表,顾名思义:数据的储存是一环扣一环的,在C语言中用结构体+指针实现。其优势是方便数据的插入、增、删、改,并且可以按照实际需求动态分配空间。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;//存放下一个结点的指针
};
int main()
{
int i,n;
scanf("%d",&n);
struct node *p,*q,*head=NULL;//head是链表的头指针,通过它找到链表
for(i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));//先动态分配内存空间,地址给p
scanf("%d",&(p->data));//p是当前要录入数据的指针
if(head==NULL)head=p;//如果是第一个结点,p赋值给头指针
else q->next=p;//否则把p给上一个结点的next
q=p;//用q记录p,所以在下一个循环中,q是上一个结点的地址
}
p->next=NULL;//最后一个结点当然没有指向啦,所以赋值为空
for(p=head;p!=NULL;p=p->next)//遍历链表
{
printf("%d ",p->data);
}
return 0;
}
想了解链表的增删改的同学请点击下面链接:
https://blog.csdn.net/tongjingqi_/article/details/105873529
想了解链表排序和查找的同学请点下面链接:
https://blog.csdn.net/tongjingqi_/article/details/105927156