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

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

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

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

struct list
{
    int val;
    struct list* next;
};

int del_list(struct list *head)
{
    struct list *tmp,*tmp_next;

    if (head->next == NULL) {
        /* 只有头结点 */
        return 0;
    }

    tmp = head->next;
    while (tmp->next != NULL) {
        tmp_next = tmp->next;
        free(tmp);
        tmp = tmp_next;
    }
    free(tmp);

    return 0;
}
int inset_node(struct list *head, struct list *new)
{
    struct list *tmp;
    tmp = head;
    while (tmp->next != NULL) {
        tmp = tmp->next;
    }
    tmp->next = new;
    return 0;
}

int find_node(struct list *head, int pos)
{
    int i;
    struct list *tmp;

    tmp = head->next;
    for (i = 0; i < pos; i++) {
        tmp = tmp->next;
    }
        printf("%d \n", tmp->val);
    return 0;
}

int main() {
    int i, k,tmp_val = 0;
    int cnt = 0;
    struct list head, *new;

    memset(&head, 0, sizeof(struct list));

/* 每个用例 分三次读取,第一次读取总数,第二循环读取节点,第三次读取k值 */
    while (scanf("%d", &cnt) != EOF) { 
        for (i = 0; i < cnt; i++) {
            scanf("%d", &tmp_val);
            /*  */
            new = (struct list *) malloc(sizeof(struct list));
            if (new == NULL) {
                del_list(&head);
                return -4;
            }
            /* 构造新的节点,作为最后一个节点 */
            new->val = tmp_val;
            new->next = NULL;
            inset_node(&head, new);
        }
        /* 输入k值 */
        scanf("%d", &k);
        if (k > cnt) {
            continue;
        }
        /* 计算出节点位置,直接正向查找 */
        find_node(&head, cnt - k );
        /* 别内存泄漏 */
        del_list(&head);
        head.next = NULL;
        
    }

    return 0;
}

全部评论

相关推荐

我面试,她问我有女朋友没
不太迷人的反派_:不过对象,还会结合你老家,意向城市等等,看你是否稳定。哥们,别多想
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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