题解 | #牛牛的单向链表#
牛牛的单向链表
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道真题和解析