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

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

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

#include <bits/stdc++.h>

using namespace::std;

struct ListNode {

int m_nKey;
ListNode *m_pNext;

};

struct ListNode *createNode(int data) {

ListNode *node = (ListNode*)malloc(sizeof(ListNode));
if (NULL == node) {
    perror("malloc error.");
    return node;
}
node->m_nKey = data;
node->m_pNext = NULL;
return node;

}

int main() {

int num = 0;

while (cin >> num) {
    int data = 0;
    int i = 0;
    int dest;
    ListNode *head = new ListNode();
    ListNode *next = head;
    for (i = 0;i < num;i++) {
        cin >> data;
        ListNode *node = createNode(data); // 后插入式单向链表
        next->m_pNext = node;
        next = node;
    }

    next = head;
    cin >> dest;
    if (dest <= 0) {
        cout << 0 << endl;
        continue;
    }
    for (i = 0;i < num - dest + 1;i++) {
        next = next->m_pNext;
    }
    cout << next->m_nKey << endl;
}

return 0;

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-05 15:27
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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