方法一:快慢指針法函數
struct Node { int data; Node *next; }; /* 函數功能:找出鏈表倒數第k個結點 輸入參數:head:鏈表頭指針(指向頭結點) 返回值:指向倒數第k個結點的指針 */ Node* findLastK(Node* head,int k) { if (head == NULL || head->next == NULL) return head; Node *slow, *fast; fast = slow = head->next; int i; for (i = 0; i < k&&fast; ++i) { fast = fast->next; } //判斷k是否已超出鏈表長度 if (i < k) return NULL; while (fast != NULL) { fast = fast->next; slow = slow->next; } return slow; }