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

牛牛的单向链表

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
    int data;
    struct node *next;
};
struct node *init_node(int data){
    struct node *head = (struct node*)malloc(sizeof(struct node));
    memset(head, 0, sizeof(struct node));
    head->data=data;
    head->next=NULL;
    return head;
}
void push(struct node *head,int data){
    struct node *new_node = init_node(data);
    struct node *p=head;
    while (p->next!=NULL) {
        p=p->next;
    }
    p->next=new_node;
}
void print_list(struct node *head){
    if(head->data==0){
        return;
    }
    struct node *p=head->next;
    while (p!=NULL) {
        printf("%d ",p->data);
        p=p->next;
    }
}
int main() {
    int n;
    scanf("%d",&n);
    struct node *head = init_node(n);
    for (int i=0; i<n; i++) {
        int val;
        scanf("%d",&val);
        push(head, val);
    }
    print_list(head);
    if (head!=NULL) {
        free(head);
        head=NULL;
    }
    return 0;
}

全部评论

相关推荐

10-01 09:50
门头沟学院 Java
肖先生~:这个人真的很好,点赞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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