题解 | #遍历链表#

遍历链表

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

#include <stdio.h>

typedef struct Node {
    int value;
    struct Node* next;
} Node;

int main() {
    int n;
    while (scanf("%d ", &n) != EOF) { // 注意 while 处理多个 case
        //带头节点
        Node* head = (Node*)malloc(sizeof(Node));
        Node* newNode, *p, *pre;
        head->value = 0;
        head->next = NULL;
        int newValue;
        for (int i = 0; i < n; i++) {
            //创建新节点
            newNode = (Node*)malloc(sizeof(Node));
            scanf("%d ", &newValue);
            newNode->value = newValue;
            newNode->next = NULL;
            //头插法
            if (i == 0) {
                head->next = newNode;
            } else {
                pre = head;
                p = head->next;
                while (p != NULL && newValue > p->value) {
                    pre=pre->next;
                    p=p->next;
                }
                newNode->next=p;
                pre->next=newNode;
            }
        }
        p=head->next;
        while(p!=NULL){
           printf("%d ",p->value);
           p=p->next; 
        }
        printf("\n");
    }
    return 0;
}

全部评论

相关推荐

11-08 13:58
门头沟学院 Java
程序员小白条:竟然是蓝桥杯人才doge,还要花钱申领的offer,这么好的公司哪里去找
点赞 评论 收藏
分享
Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务