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

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

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

#include <iostream>
using namespace std;

struct ListNode {
    int m_nKey;
    ListNode* m_pNext;

    ListNode(int x): m_nKey(x), m_pNext(nullptr) {}
};

int main() {
    ListNode* dummy = new ListNode(-1);
    ListNode* cur = dummy;
    int n;
    cin >> n;
    while (true) {
        for (int i = 0; i < n; ++i) {
            int val;
            cin >> val;
            ListNode* node = new ListNode(val);
            cur->m_pNext = node;
            cur = cur->m_pNext;
        }
        int k;
        cin >> k;
        cur = dummy->m_pNext;
        // while(cur){
        //     cout << cur->m_nKey << " ";
        //     cur = cur->m_pNext;
        // }
        ListNode* fast = cur;
        ListNode* slow = cur;
        while (k--) {
            fast = fast->m_pNext;
        }
        while (fast) {
            slow = slow->m_pNext;
            fast = fast->m_pNext;
        }

        cout << slow->m_nKey << endl;
        if(!(cin >> n)){
            break;
        }
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务