鏈表,顧名思義:數據的儲存是一環扣一環的,在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