链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

题目链接:https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&&tqId=11167&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

代码:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(k<=0||pListHead==NULL) return NULL;
        ListNode *fast=pListHead,*slow=pListHead;
        int tmp=k;
        while(tmp--)
        {
            if(fast) fast=fast->next;
            else return NULL;
        }
        while(fast)
        {
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
};

 

你可能感兴趣的:(剑指offer)