1-5 头插法创建单链表(C) 分数 7
作者 李廷元
单位 中国民用航空飞行学院
本题要求实现两个函数,输入n个数据,采用头插法创建单链表并打印。例如:如果输入4 ,再输入3 7 9 5,则应打印输出5 9 7 3。
链表结点结构定义: 1 2 3 4 struct Node { int data; struct Node * link ; };
函数接口定义: 1 2 3 struct Node* buildLinkedList (int * arr, int n) ; void printLinkedList (struct Node* head) ;
其中arr和n是用户传入的参数,n的值不超过100000。head为单链表的头指针。
裁判测试程序样例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node * link ; }; struct Node* buildLinkedList (int * arr, int n) ; void printLinkedList (struct Node* head) ; int main (int argc, char const *argv[]) { int n, i; int * a; scanf ("%d" , &n); a = (int *)malloc (n * sizeof (int )); for (i = 0 ; i < n; ++i) { scanf ("%d" , &a[i]); } struct Node * head = NULL ; head = buildLinkedList(a, n); printLinkedList(head); free (a); return 0 ; }
输入样例: 输入包含两行。 第一行为数据个数n,不超过100000。 第二行为n个空格分隔的整数,其值不超过int值的范围。
输出样例: 在一行输出链表每个结点中的数据,以空格分隔,但行尾无多余空格。
带头结点答案 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 struct Node* buildLinkedList (int * arr, int n) { struct Node *head = (struct Node*) malloc (sizeof (struct Node)); head->link = NULL ; int i = 0 ; while (i < n) { struct Node *newNode = (struct Node*) malloc (sizeof (struct Node)); newNode->data = arr[i]; newNode->link = head->link; head->link = newNode; i++; } return head; } void printLinkedList (struct Node* head) { struct Node * p = head->link; int isFront = 1 ; while (p != NULL ) { if (!isFront) { printf (" " ); } printf ("%d" , p->data); isFront = 0 ; p = p->link; } }
不带头结点答案 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 struct Node* buildLinkedList (int * arr, int n) { struct Node * head = NULL ; int i; for (i = 0 ; i < n; i++) { struct Node * newNode = (struct Node*)malloc (sizeof (struct Node)); newNode->data = arr[i]; newNode->link = head; head = newNode; } return head; } void printLinkedList (struct Node* head) { struct Node * p = head; int isFront = 1 ; while (p != NULL ) { if (!isFront) { printf (" " ); } printf ("%d" , p->data); isFront = 0 ; p = p->link; } }