找寻链表的倒数K个结点

来源:互联网 发布:詹姆斯赛季数据 编辑:程序博客网 时间:2024/06/18 11:20

想法就是用两个指针遍历链表,第一个指针先走K-1步,紧接着第二个指针同时开始走,当第一个指针走到链表末尾时,第二个指针刚好指向倒数第K个结点,算法结束。

点评:

1注意防御性编程 :链表不能为空指针,K不能小于0;2当链表长度小于K时,要有处理机制,返回NULL;

struct ListNode{intm_nValue;ListNode* m_pNext;};ListNode* FindKthListNode(ListNode* pHeadList, unsigned K){if (pHeadList == NULL || K == 0)return NULL;//防御性编程ListNode* pAhead = pHeadList;ListNode* pBehind = NULL;for (int i = 0; i < K; ++i){if (pAhead->m_pNext != NULL)//注意这里,当pHeadList长度小于K时,返回NULLpAhead = pAhead->m_pNext;elsereturn NULL;}pBehind = pHeadList;while (pAhead != NULL){pAhead = pAhead->m_pNext;pBehind = pBehind->m_pNext;}return pBehind;}


0 0
原创粉丝点击