题解 | #链表中倒数第k个结点#

链表中倒数第k个结点

https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a

/*
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* re=pListHead;
		ListNode* pre=pListHead;
		if (pListHead==nullptr) {
			return nullptr;
		}
		while (k-->0) {
			if (pre!=nullptr) {
				pre=pre->next;
			}
			else {
				return nullptr;
			}
		}
		while (pre!=nullptr) {
			pre=pre->next;
			re=re->next;
		}
		return re;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务