题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <iostream>
using namespace std;
struct ListNode {
int m_nKey;
ListNode* m_pNext;
};
int main() {
int node_len;
while (cin >> node_len) {
ListNode head{0, nullptr};
ListNode* curr = &head;
while (node_len--) {
int value;
cin >> value;
auto* next = new ListNode{value, nullptr};
curr->m_pNext = next;
curr = next;
}
int k;
cin >> k;
auto slow = head.m_pNext;
auto fast = head.m_pNext;
while (k-- && fast) {
fast = fast->m_pNext;
}
if (k <= 0) {
while (fast) {
fast = fast->m_pNext;
slow = slow->m_pNext;
}
}
cout << slow->m_nKey << endl;
}
}
// 64 位输出请用 printf("%lld")
查看1道真题和解析
腾讯成长空间 6042人发布