链表--查找单链表的倒数第k个节点,要求只能遍历一次链表

来源:互联网 发布:如何判断是否怀孕 知乎 编辑:程序博客网 时间:2024/05/21 09:18

思路:
给出两个指针pFast和pSlow,先让pFast指针走K步,再同时走两个指针。
当pFast走到结尾的时候,此时的pSlow为倒数第K个节点。

ListNode* FindKNode(ListNode* pHead,int k){     if(k<=0 || pHead ==NULL )          return NULL;     ListNode* pFast = pHead;     ListNode* pSlow = pHead;     while(k!=0 && pFast != NULL)     {           k--;           pFast = pFast->Next;         }     //这里可能k>链表长度,所以判断pFast是否为空     if(pFast == NULL)          return NULL;     while(pFast != NULL)     {          pFast = pFast->Next;          pSlow = pSlow->Next;     }     return pSlow;}
阅读全文
0 0