题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <iostream>
using namespace std;
struct ListNode{
int m_nKey;
ListNode* m_pNext = NULL;
};
int main() {
int n;
while (cin >> n) {
ListNode* head = new ListNode;
ListNode* curr = head;
for(int i = 0; i < n; i++){
ListNode* node = new ListNode;
int val;
cin >> val;
node->m_nKey = val;
curr->m_pNext = node;
curr = node;
}
int k;
cin >> k;
ListNode* fast = head->m_pNext;
ListNode* slow = head->m_pNext;
while(k>0) {
fast = fast->m_pNext;
k--;
}
while(fast!=NULL){
fast = fast->m_pNext;
slow = slow->m_pNext;
}
cout << slow->m_nKey << endl;
}
return 0;
}
// 64 位输出请用 printf("%lld")
