题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(nullptr){}
};
ListNode* findKthTOtail(ListNode* head, int k){
ListNode *fast = head, *slow = head;
while(k--){
if(fast != nullptr) fast = fast->next;
else return nullptr;
}
while(fast != nullptr){
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main() {
int n;
while(cin>>n){
int val;
cin>>val;
ListNode *head = new ListNode(val);//链表第一个结点
ListNode *p = head;
for(int i = 1; i < n; i++){//输入链表后续结点
cin>>val;
p->next = new ListNode(val);
p = p->next;
}
int k;
cin>>k;
if(k == 0) cout<< 0<< endl;
else {
p = findKthTOtail(head, k);
if(p != nullptr) cout<<p->val<<endl;
}
}
return 0;
}

查看13道真题和解析