题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <bits/stdc++.h>
using namespace::std;
struct ListNode {
int m_nKey;
ListNode *m_pNext;
};
struct ListNode *createNode(int data) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
if (NULL == node) {
perror("malloc error.");
return node;
}
node->m_nKey = data;
node->m_pNext = NULL;
return node;
}
int main() {
int num = 0;
while (cin >> num) {
int data = 0;
int i = 0;
int dest;
ListNode *head = new ListNode();
ListNode *next = head;
for (i = 0;i < num;i++) {
cin >> data;
ListNode *node = createNode(data); // 后插入式单向链表
next->m_pNext = node;
next = node;
}
next = head;
cin >> dest;
if (dest <= 0) {
cout << 0 << endl;
continue;
}
for (i = 0;i < num - dest + 1;i++) {
next = next->m_pNext;
}
cout << next->m_nKey << endl;
}
return 0;
}