题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <cstdlib>
#include <iostream>
#include <malloc.h>
#include <vector>
using namespace std;
struct ListNode {
int m_nKey;
ListNode* m_pNext;
};
int main() {
int n, k;
while (cin >> n) {
// cout << n << endl;
int i = 0, temp, n1=n;
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
head->m_nKey = n;
head->m_pNext = nullptr;
ListNode* cur = head;
while (n--) { // 注意 while 处理多个 case
cin >> temp;
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->m_nKey = temp;
node->m_pNext = nullptr;
cur->m_pNext = node;
cur = cur->m_pNext;
// cout << cur->m_nKey << endl;
}
cin >> k;
// cout<<"diyibian"<<endl;
cur = head;
// cout<<cur->m_pNext->m_nKey;
int pos=n1+1-k;
// cout<<pos<<endl;
while (cur && pos) {
cur=cur->m_pNext;
pos--;
if (pos==0) {
cout<<cur->m_nKey<<endl;
}
}
if (!cur) {
cout<<"0"<<endl;
}
free(head);
}
}
// 64 位输出请用 printf("%lld")

美团成长空间 2666人发布
