数据结构实验之链表一:顺序建立链表
Problem Description
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
Input
第一行输入整数的个数N;
第二行依次输入每个整数。
第二行依次输入每个整数。
Output
输出这组整数。
Example Input
8
12 56 4 6 55 15 33 62
Example Output
12 56 4 6 55 15 33 62
Hint
不得使用数组!
Author
分析:
首先,题目没有说明长度,不方便使用数组。
其次,要求不能够用数组,想到要用链表来实现。
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&链表与数组比较&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
二者都属于一种数据结构 从逻辑结构来看 1. 数组必须事先定义固定的长度,不能适应数据动态地增减的情况。 当数据增加时,可能超出原先定义的元素个数; 当数据减少时,造成内存浪费; 数组可以根据下标直接存取。 2. 链表动态地进行存储分配,可以适应数据动态地增减的情况,且可以方便地插入、删除数据项。 链表必须根据next指针找到下一个元素。 从内存存储来看 1. (静态)数组从栈中分配空间, 对于程序员方便快速,但是自由度小 2. 链表从堆中分配空间, 自由度大但是申请管理比较麻烦 因此,如果需要快速访问数据,很少或不插入和删除元素,就应该用数组; 相反, 如果需要经常插入和删除元素就需要用链表数据结构了。代码:
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node * next; }; struct node * creat(struct node * head, int n) { struct node * tail, *p; tail = (struct node *)malloc(sizeof(struct node)); tail = head; while(n--) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d", &p->data); tail->next = p; tail = p; } return head; } void show(struct node * head) { struct node * p; p = (struct node *)malloc(sizeof(struct node)); p = head->next; while(p!=NULL) { while(p->next!=NULL) { printf("%d ", p->data); p = p->next; } printf("%d\n", p->data); p = NULL; } } int main() { struct node *head; int a; head = (struct node *)malloc(sizeof(struct node)); scanf("%d", &a); creat(head, a); show(head); return 0; }