题解 | #牛牛的单向链表#

牛牛的单向链表

https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4

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

typedef struct node {
    int data;
    struct node* next;
} Node;

Node* createFirstNode() {
    Node* Head = (Node*)malloc(sizeof(Node));
    if (Head == NULL) {
        printf("Fail!\n");
        return NULL;
    }
    Head->next = NULL;
    return Head;
}

void insertNum(Node* Head, int num) {
    Node* temp = (Node*)malloc(sizeof(Node));
    if (temp == NULL) {
        printf("Fail!\n");
        return ;
    }
    temp->data = num;
    temp->next = NULL;

    Node* current = Head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = temp;
}

void printList(Node* Head) {
    Node* current = Head->next;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    int n;
    scanf("%d", &n);
    Node* Head = createFirstNode();
    int num;
    while(scanf("%d",&num)!=EOF) {
        insertNum(Head,num);
    }
    printList(Head);

    Node* current = Head;
    while (current->next != NULL) {
        Node* current_ret = current;
        current = current->next;
        free(current_ret);
    }

    return 0;
}

全部评论

相关推荐

05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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