剑指offer :倒数第K个节点

题目描述:输入一个链表,输出该链表中倒数第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)
	{
		ListNode* node = pListHead;
		int count;
		//遍历链表  得到节点数   
		while (node)
		{
			count++;
			node = node->next;
		}
		//如果要查找的倒数第K个节点大于count  返回空;
		if (k > count)
			return nullptr;
		//要找的是倒数第K个也就是从开始的第count-K个节点

		int number_k = count - k;
		node = pListHead;
		if (number_k >= 0)
		{
			while (number_k--)
			{
				node = node->next;
			}
			return node;
		}
		else
		{
			return nullptr;
		}
	}
};

猜你喜欢

转载自blog.csdn.net/Shile975/article/details/88825842
今日推荐