题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <cstddef> #include <iostream> using namespace std; struct ListNode{ //链表结点 int val;//数据域 ListNode* next;//指针域 //构造函数 //ListNode(int x) : val(x), next(nullptr){} //初始化,头节点 ListNode(int x) { val = x; next = nullptr; } }; // 遍历链表 void printList(ListNode* head) { ListNode* curr = head; while (curr != nullptr) { std::cout << curr->val << " "; curr = curr->next; } std::cout << std::endl; } int main() { int a; while (cin >> a) { int val; cin >> val; ListNode* head = new ListNode(val); //创建头节点 ListNode* curr = head; for (int i = 1;i < a;i++) { int data; cin >> data; ListNode* newNode = new ListNode(data); curr->next = newNode; //将创建的节点域上一个链接起来 curr = newNode; //将当前节点更新到下一个节点上 } //链表创建完后,curr会指向最后一个创建LinkNode结构体, //如果要打印,就要将指针,指向头节点 // ListNode* ptr = head; // while(ptr != NULL) // { // cout << ptr->val << " "; // //更新结构体指针curr // ptr = ptr->next; // } int k; cin >> k; ListNode* fast = head; //指向头结构体 for (int i = 0;i < k;i++) { if(fast == NULL) { cout << "没有这个节点" << endl; } fast = fast->next; } ListNode* slow = head; while (fast != nullptr) { fast = fast->next; slow = slow->next; } cout << slow->val << endl; } } // 64 位输出请用 printf("%lld")