题解 | #牛牛的单向链表#
牛牛的单向链表
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; }