連結串列倒數第k個結點

辰星~發表於2020-10-04

輸入一個連結串列,輸出該連結串列中倒數第k個結點。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
	ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
		//快慢指標,轉化為正數第幾個
		unsigned int temp = k;
		ListNode* fast = pListHead;
		if (temp == 0)
			return nullptr;
		//先走到正數第K+1個
		while (temp--) {
			if (fast)
				fast = fast->next;
			else
				return nullptr;
		}
		//快指標走到尾,慢指標就走到了倒數第K個
		ListNode* slow = pListHead;
		while (fast) {
			fast = fast->next;
			slow = slow->next;
		}
		return slow;
	}
};

相關文章