题解 | 牛牛的单向链表
牛牛的单向链表
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;
}
三奇智元机器人科技有限公司公司福利 74人发布