题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
http://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
typedef struct ListNode Node;
Node* find(Node* pHead, int k)
{
Node* tmp = pHead;
int i;
if (pHead == NULL||k<=0)
return NULL;
for (i = 0; i < k-1; i++)
{
if (tmp->next == NULL)
return NULL;
tmp = tmp->next;
}
return tmp;
}
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
Node* tmpH = pHead;
Node* tmpK = find(pHead, k);
if (!tmpK || !tmpH||k<=0)
return NULL;
while (tmpK->next != NULL)
{
tmpH = tmpH->next;
tmpK = tmpK->next;
}
return tmpH;
}