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

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

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

链表

#include <stdio.h>
#include <string.h>

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

int main(void) {
    int n, k;
    int num[1001] = {0};

    while (scanf("%d", &n) != EOF) {

        ListNode* head = (ListNode*)malloc(sizeof(ListNode));
        ListNode* temp = head;


        for (int i = 0; i < n; ++i) {
            scanf("%d", &num[i]);
        }

        for (int j = 0; j < n; ++j) {
            ListNode* current = (ListNode*)malloc(sizeof(ListNode));
            current->m_nKey = num[j];
            current->m_pNext = NULL;
            temp->m_pNext = current;
            temp = current;

        }
        
        temp = head;
        int m = 0;
        while (temp->m_pNext) {
            temp = temp->m_pNext;
            m++;
        }

        scanf("%d", &k);

        temp = head;
        temp = temp->m_pNext;
        for (int a = 0; a < m - k; ++a) {
            temp = temp->m_pNext;
        }
        printf("%d\n", temp->m_nKey);
    }

    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 15:46
已编辑
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
蚂蚁 基架java (n+6)*16 签字费若干
点赞 评论 收藏
分享
尊尼获获:闺蜜在哪?
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务