题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

// 输入输出
#include <iostream> 
#include <stdio.h>
#include <sstream>
#include <cctype>

// 数据结构
#include <string>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <queue>

// 算法
#include<algorithm>

// namespace
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::stringstream;
using std::to_string;
using std::vector;
using std::map;
using std::set;
using std::unordered_map;
using std::unordered_set;
using std::priority_queue;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x, ListNode *next = nullptr) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && k-- > 0) fast = fast->next;
        while (fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

int main() {
    // 处理输入数据
    int n;
    while (cin >> n) {
        getchar();
        string line;
        getline(cin, line);
        stringstream ss(line);

        int k;
        cin >> k;

        int val;
        ss >> val;
        ListNode* head = new ListNode(val);
        ListNode* p = head;
        while (ss >> val) {
            p->next = new ListNode(val);
            p = p->next;
        }

        Solution solve;
        // 输入数据, 调用核心函数, 得到输出结果
        auto res = solve.getKthFromEnd(head, k);
        printf("%d\n", res->val);
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务