题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <iostream>
using namespace std;
struct ListNode {
int m_nKey;
ListNode* m_pNext;
ListNode(int data, ListNode *next) {
m_nKey = data;
m_pNext = next;
}
};
int main()
{
int n, data, k, count = 0;
ListNode* head = NULL, *cur = NULL, *result = NULL;
while(cin >> n) {
cin >> data;
head = cur = new ListNode(data, NULL);
for (int i = 1; i < n; i++) {
cin >> data;
ListNode* node = new ListNode(data, NULL);
cur->m_pNext = node;
cur = cur->m_pNext;
}
cin >> k;
cur = head;
while (cur != NULL) {
cur = cur->m_pNext;
count++;
if (result != NULL) { //要在count == k才能同步
result = result->m_pNext;
}
if (count == k) {
result = head;
}
}
if (result != NULL)
cout << result->m_nKey << endl;
else
cout << 0 << endl; //异常返回空指针,编译要输0, 踩了好久的坑
count = 0;
head = cur = result = NULL;
}
return 0;
}