考慮特殊情況:
1. 鏈表頭指標為空白,n小於等於0是錯誤輸入
2. 鏈表實際節點數小於n
因此代碼:
#include <stdio.h>#include <stdlib.h>typedef struct node{ int a; struct node *link; }mynode;int creat_tail(mynode *head,int n){ mynode *node = head,*new; int x; if(n <= 0){ printf("error: n <= 0"); return 0; } for(;n > 0;n--){ new = (mynode*)malloc(sizeof(mynode)); printf("enter a number:\n"); scanf("%d",&x); new->a = x; new->link = NULL; node->link = new; //隨動指標 node = node->link; } }mynode* search(mynode *head,int n){ mynode *front = head,*behind = head; if(head == NULL || n <= 0) return NULL; while(front->link != NULL && n > 0){ front = front->link; n--; } if(n > 0) return NULL; while(front != NULL){ front = front->link; behind = behind->link; } return behind;}//正向列印 void print_nodes1(mynode *head){ int n = 1; mynode *node; if(head != NULL){ node = head->link; while(node != NULL){ printf("num:%d\t a=%d\n",n,node->a); node = node->link; n++; } } } void main(){ mynode *head,*value; creat_tail(head,1); print_nodes1(head); value = search(head,1); printf("%d\n",value->a); getch();}