题解 | #牛牛的单向链表#
牛牛的单向链表
https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4
#include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; }node; node *createlist()//创建一个头节点,头节点的指针域置空 { node *head = malloc(sizeof(node)); if(head == NULL) { printf("内存分配失败\n"); exit(1); } head->next = head; return head; } void insertlist(node *head,int data) { node *new = malloc(sizeof(node)); if(new == NULL) { printf("out of memory"); exit(1); } new->data = data; new->next = NULL; node *p = NULL; for(p = head; p->next != head; p = p->next); new->next = p->next; p->next = new; } void output(node *head) { if (head->next == head) { return; } node *p = head->next; while (p != head) { printf("%d ", p->data); p = p->next; } } int main(void) { node *head = createlist();//创建一个头节点 int n,i,j; scanf("%d", &n); int arr[n]; for (i = 0; i < n; i++) { scanf("%d", &arr[i]); } //将数据插入链表 for(j = 0; j < n; j++) insertlist(head,arr[j]); output(head); return 0; }