题解 | #遍历链表#

遍历链表

https://www.nowcoder.com/practice/7d348aa8b7d24e01a4f10bd023e2fb54

链表其实非常简单,主要是结构体的定义比较烦人,个人其实还是更加偏向用类的方式来实现,但是c没有,┭┮﹏┭┮

#include <stdio.h>

typedef struct node{
    int val;
    struct node* next;
} node;

int main() {
    int n;
    node* root = (node *)malloc(sizeof(node));
    root->val = -9999;
    node* pre = root;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        int val;
        scanf("%d", &val);
        node* nd = (node *)malloc(sizeof(node));
        nd->val = val;
        if (val > pre->val) {
            pre->next = nd;
            pre = pre->next;
        } else {
            node* p = root;
            while (p->next->val < val) {
                p = p->next;
            }
            nd->next = p->next;
            p->next = nd;
        }
    }
    while (root->next) {
        root = root->next;
        printf("%d ", root->val);
    }
    printf("\n");
    return 0;
}

全部评论

相关推荐

牛客773130651号:巨佬,简历模板换成上下的,左右的很烦,hr看着不爽。。。科大随便乱杀,建议能保研就保研,不行也得考一下 ,985硕去干算法,比开发强多了。开发许多双非都能搞,学历优势用不上,算法有门槛
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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