如果对数组的数据进行加一项的操作时,数组大小需要重新操作。而链表只需要让原有的链表指向新加入的链表,即可添加元素。
- #include
-
- struct Test
- {
- int data;
- struct Test *next;
- };
-
- void printLink(struct Test *head) //传递链表地址
- {
- while(1){
- if(head != NULL){ //判断链表是否为空地址
- printf("%d ",head->data); //是,打印里面的元素
- head = head->next;
- }else{
- printf("\n");
- break; //否,停止程序
- }
- }
- }
- int main(){
- struct Test t1 = {1,NULL};
- struct Test t2 = {2,NULL};
- struct Test t3 = {3,NULL};
- struct Test t4 = {4,NULL};
-
- t1.next = &t2;
- t2.next = &t3;
- t3.next = &t4;
-
- printLink(&t1); //调用函数,传递首个链表地址
- return 0;
- }
链表统计:
用循环语句判断指针是否为空,不为空则让代数+1,否则停止返回总数,最后打印
- int getLinkNum(struct Test *head)
- {
- int cnt =0;
- while(head !=NULL){
- cnt ++;
- head = head->next;
- }
- return cnt;
- }
-
- int ret =getLinkNum(&t1);
- printf("total num = %d\n",ret);
链表查找:
链表查找功能的实现需要链表地址和你要查找的数据,循环语句中判断是否为空指针,再进行判断,最后进行链表地址的指向。
- int searchLink(struct Test *head,int data)
- {
- while(head != NULL){
- if(head->data == data){
- return 1;
- }
- head = head->next;
- }
- return 0;
- }
-
- int main(){
- struct Test t1 = {1,NULL};
- struct Test t2 = {2,NULL};
- struct Test t3 = {3,NULL};
- struct Test t4 = {4,NULL};
-
- t1.next = &t2;
- t2.next = &t3;
- t3.next = &t4;
-
- ret = searchLink(&t1,1);
- if(ret = 0){
- printf("没有data = 1\n");
- }else{
- printf("有data = 1\n");
- }
- return 0;
- }