题解 | 输出单向链表中倒数第k个结点
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode():val(-1),next(nullptr){}
ListNode(int x):val(x),next(nullptr){}
ListNode(int x,ListNode* next):val(x),next(next){}
};
int getnode(ListNode* head,int k){
ListNode* fast = head;
ListNode* slow = head;
for(int i=0;i<k;i++){
fast = fast->next;
}
while(fast){
fast = fast->next;
slow = slow->next;
}
return slow->val;
}
int main() {
int node_num;
int num;
int ret;
while(cin >> node_num){
ListNode* head = new ListNode();
ListNode* cur = nullptr;
ListNode* ptr = head;
for(int i=0;i<node_num;i++){
//ListNode* ptr = head;
cin >> num;
cur = new ListNode(num);
ptr->next = cur;
ptr = cur;
}
cur = head->next;
cin >> num;
ret = getnode(cur,num);
cout << ret << endl;
}
return 0;
}
利用快慢指针进行求解

影石Insta360公司氛围 452人发布
查看22道真题和解析