#include //定义结构体 struct Test {int data;struct Test *next;//链表有一个指向自己的指针 };intmain() {putchar('\n');//定义结构体变量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("%d %d %d %d %d \n",t1.data, t1.next->data, t1.next->next->data, t1.next->next->next->data, t1.next->next->next->next->data);return0; }
执行结果:
我们优化一下上边程序的写法:
#include //定义结构体 struct Test {int data;struct Test *next;//链表有一个指向自己的指针 }; //输出链表数据 voidprintLink(struct Test *head) {struct Test *piont = head;while(piont !=NULL){printf("%d ",piont->data);piont = piont->next;}putchar('\n'); } intmain() {//定义结构体变量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("%d %d %d %d %d \n",t1.data, t1.next->data, t1.next->next->data, t1.next->next->next->data, t1.next->next->next->next->data);printLink(&t1);putchar('\n');return0; }
#include //定义结构体 struct Test {int data;struct Test *next;//链表有一个指向自己的指针 };//获取列表节点数 intgetLink(struct Test *head) {int cnt =0;struct Test *piont = head;while(piont !=NULL){cnt++;piont = piont->next;}return cnt; }intmain() {//定义结构体变量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;int ret =getLink(head);printf("the link's is %d \n",ret);return0; }
执行结果:
链表数据查找
#include //定义结构体 struct Test {int data;struct Test *next;//链表有一个指向自己的指针 }; //查找数据 intsearchLink(struct Test *head,int data) {while(head !=NULL){if(head->data == data){//如果输入的数据与链表里的某一项数据相等就返回1否则返回0return1;}//跳到下一节点head = head->next;}return0; }intmain() {//定义结构体变量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;//定义、输入数据int num;scanf("%d",&num);int ret =searchLink(&t1,num);//结果返回if(ret){printf("have %d\n",num);}else{printf("don't have %d\n",num);}return0; }