题解 | 牛牛的单向链表

牛牛的单向链表

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

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

//这里我们定义一个结构体,这么定义可以偷懒
typedef struct array{  
    int num;
    struct array *next;
}node;
//定义一个输出函数
void print(node *head){ //head也就是主函数中的头指针
    node*p=head;
    while(p!=NULL){
        printf("%d ",p->num);//输出num;
        p=p->next;
    }
}
void allclean(node **list){ //回收内存 **list是个二级指针 *list的值为我们要指向的指针的地址(*list=head)
    node *p=(*list);
    while (p!=NULL) {
    (*list)->next=p->next;
    free(p);
    p=(*list)->next;
    }
    free(*list);
    (*list)=NULL;
}
int main() {

    int n;
    scanf("%d",&n);

    int* arr=(int*)malloc(n*sizeof(int));

    for (int i = 0; i < n; i++) {
        scanf("%d",&arr[i]);
    }

    // 定义指针,构造链表
    node *head,*tail,*p;
    head=tail=NULL;
    for(int i=0;i<n;i++){
    p=(node*)malloc(sizeof(node));
    p->num=arr[i];
    p->next=NULL;
    if(head==NULL){
        head=p;
    }
    else {
    tail->next=p;
    }
    tail=p;
    }
    print(head);
    allclean(&head);
    free(arr);
    return 0;
}



全部评论
求讨论
1 回复 分享
发布于 01-05 21:14 江西

相关推荐

评论
1
收藏
分享

创作者周榜

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