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

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

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

#include <iostream>
using namespace std;
struct ListNode {
    int m_nKey;
    ListNode* m_pNext;
    ListNode(int data, ListNode *next) {
        m_nKey = data;
        m_pNext = next;
    }
};
int main()
{
    int n, data, k, count = 0;
    ListNode* head = NULL, *cur = NULL, *result = NULL;
    while(cin >> n) {
        cin >> data;
        head = cur = new ListNode(data, NULL);
        for (int i = 1; i < n; i++) {
            cin >> data;
            ListNode* node = new ListNode(data, NULL);
            cur->m_pNext = node;
            cur = cur->m_pNext;
        }
        cin >> k;
        cur = head;
        while (cur != NULL) {
            cur = cur->m_pNext;
            count++;
            if (result != NULL) { //要在count == k才能同步
                result = result->m_pNext;
            }
            if (count  == k) {
                result = head;
            }

        }
        if (result != NULL)
            cout << result->m_nKey << endl;
        else
            cout << 0 << endl; //异常返回空指针,编译要输0, 踩了好久的坑
        count = 0;
        head = cur = result = NULL;
        
    }
    return 0;
}
全部评论

相关推荐

11-26 22:34
已编辑
重庆邮电大学 Java
快手 客户端开发 (n+5)k*16 公积金12
牛客895077908号:佬 什么双非硕啊
点赞 评论 收藏
分享
斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
M_bao:换个排版吧哥们,看着费劲
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务