輸入一個單向鏈表,輸出該鏈表中倒數第 k 個結點。鏈表的倒數第 0 個結點爲鏈表的尾指針。node
算是比較簡單的題目了。spa
解法一:指針
能夠先遍歷一遍統計鏈表個數,而後找到倒數第k個的下標再遍歷,這樣時間複雜富比較高
code
解法二:io
雙指針聯動,一個指針先跑K個節點,而後兩個指針一塊兒跑,一個指針跑到尾節點時另外一個指針剛好是倒數第K個節點。
編譯
解法二(GCC編譯經過):ast
#include "stdio.h" #include "stdlib.h" //鏈表長度 #define N 50 //鏈表節點定義 typedef struct node { int date; struct node * next; }link; link * lastK(link * head,int k); int main(void) { link * head, *p; int i; //隨機數種子 srand((unsigned int)time(0)); //生成鏈表 head = p = (link *)malloc(sizeof(link)); head-> date = rand()%101; head-> next = NULL; for(i=1;i<N;i++) { p = p->next = (link *)malloc(sizeof(link)); p->date = rand()%101; p->next = NULL; } //輸出鏈表 for(p = head;p;p=p->next) printf("%d ",p->date); //產生K i = rand()%100; printf("\n隨機生成一個K:%d",i); //輸出倒數第K個數 p = lastK(head,i); if(p == NULL) printf("錯誤!\n"); else printf("\n倒數第%d個數是%d\n",i,p->date); } link * lastK(link * head,int k) { link * p,* q; p = q = head; if(k<=0) return NULL; //兩個指針,q先跑個保證p最後指向的是倒數第K個 while(k-1 > 0) { if(q->next!=NULL) q = q->next; else return NULL; k--; } while(q->next != NULL) { p = p->next; q = q->next; } return p; }