链表是特殊的结构体,他跟数组最大的不同是,数组的连续空间来存放数据,链表的随机空间,通过结构体指针的方式来将每个连接起来。下面是一个简单的存放数组的案例。
#include<stdio.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test* head)
{
struct Test* point=head;
while(point!=NULL){
printf("%d ",point->data);
point=point->next;
}
}
int getNum(struct Test* head)
{
int num=0;
struct Test* point=head;
while(point!=NULL){
num++;
point=point->next;
}
return num;
}
int searchNum(struct Test* point,int data)
{
while(point!=NULL){
if(point->data==data){
return 1;
}
point=point->next;
}
return 0;
}
int main()
{
int i;
int array[]={1,2,3};
for(i=0;i<sizeof(array)/sizeof(array[0]);i++){
printf("%d\n",array[i]);
}
struct Test t1={1,NULL};
struct Test t2={2,NULL};
struct Test t3={3,NULL};
struct Test t4={4,NULL};
struct Test t5={5,NULL};
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
t4.next=&t5;
printf("use t1 to print three nums!\n");
printLink(&t1);
putchar('\n');
int ret=getNum(&t1);
printf("链表里的个数是:%d\n",ret);
ret = searchNum(&t1,1);
if(ret==0){
printf("no 1\n");
}
else{
printf("have 1\n");
}
ret = searchNum(&t1,8);
if(ret==0){
printf("no 8\n");
}
else{
printf("have 8\n");
}
return 0;
}