一、问题
查找链表的中间节点
查找链表的倒数第k个结点
二、解决思路:快慢指针
找中间节点:快指针走两步,慢指针走一步
找倒数第k个结点:快指针走k步或k-1步,然后慢指针再开始走
三、代码实现(c语言)
1.找中间结点
sListNode* FindMidNode(sListNode* pHead) { sListNode* slow = pHead, *fast = pHead; while(fast!=NULL && fast->next!=NULL) { slow = slow->next; fast = fast->next->next; } return slow;
2.找倒数第k个结点
sListNode* FindKTailNode(sListNode* pHead,int k) { assert(k >= 0); sListNode* fast = pHead, *slow = pHead; while(--k) //快指针走k-1步 { if(fast->next == NULL) return NULL; fast = fast->next; } while(fast->next != NULL) { slow = slow->next; fast = fast->next; } return slow; }