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

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

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

#include <cstdlib>
#include <iostream>
#include <malloc.h>
#include <vector>
using namespace std;

struct ListNode {
    int m_nKey;
    ListNode* m_pNext;
};

int main() {
    int n, k;

    while (cin >> n) {
        // cout << n << endl;
        int i = 0, temp, n1=n;
        
        ListNode* head = (ListNode*)malloc(sizeof(ListNode));
        head->m_nKey = n;
        head->m_pNext = nullptr;

        ListNode* cur = head;

        while (n--) { // 注意 while 处理多个 case
            cin >> temp;
            ListNode* node = (ListNode*)malloc(sizeof(ListNode));
            node->m_nKey = temp;
            node->m_pNext = nullptr;
            cur->m_pNext = node;
            cur = cur->m_pNext;
            // cout << cur->m_nKey << endl;
        }
        cin >> k;
        // cout<<"diyibian"<<endl;
        cur = head;
        // cout<<cur->m_pNext->m_nKey;
        int pos=n1+1-k;
        // cout<<pos<<endl;
        while (cur && pos) {
            cur=cur->m_pNext;
            pos--;
            if (pos==0) {
                cout<<cur->m_nKey<<endl;
            }
        }
        if (!cur) {
            cout<<"0"<<endl;
        }
        free(head);
    }

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

全部评论

相关推荐

码农索隆:传音老登来也。 但是这个我不知道怎么回答,不仅仅传音吧,很多公司在候选人不第一时间接受offer或主动将报道时间延期时,都会再从池子里面捞人,直到l捞到满足公司所有要求的人。
秋招的第一个offer,...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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