华为OJ基础篇-输出单向链表中倒数第k个结点

输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第0个结点为链表的尾指针。

struct ListNode{
	int mKey;
	ListNode* mNext;
};
void HWoj(){
	ListNode *head, *p, *q, *t;
	head = NULL;
	int N,tmp=0;
	cin >> N;
	for (int i = 0; i < N; ++i){
		cin >> tmp;
		p = new ListNode;
		p->mKey = tmp;
		p->mNext = NULL;
		if (head == NULL)
			head = p;
		else
		{
			q->mNext = p;
		}
		q = p;
	}
	t = head;
	int ptr = 0,count=0;
	cin >> ptr;
	while (t != NULL){
		if (count == N - ptr-1){ cout << t->mKey; break; }
		else{ ++count; t = t->mNext; }
		if (ptr > N||ptr<0){break; }
	}
	cout << endl;
}


你可能感兴趣的:(C++,链表)