基本思路:
(1)将pSlow和pFast同时指向链表的头部
(2)将快指针向后移动K位
(3)快慢指针同时移动,当pFast为空时,pSlow就指向倒数第K个节点
(4)结束
算法:
1 LinkList* FindK(LinkList* LK,int K){ 2 LinkList *pSlow,*pFast; 3 pSlow=pFast=LK; 4 int i=0; 5 while(i<K){ 6 pFast=pFast->next; 7 i++; 8 } 9 while(pFast){ 10 pSlow=pSlow->next; 11 pFast=pFast->next; 12 } 13 return pSlow; 14 }
本文介绍了一种用于找到链表倒数第K个节点的算法,通过快慢指针的方法实现,提高了查找效率。算法详细步骤包括初始化快慢指针到链表头部、快指针先前进K步、同步移动直至快指针到达链表末尾时,慢指针所指即为倒数第K个节点。
570

被折叠的 条评论
为什么被折叠?



