程序功能:建立一个单向链表,并将存储在数组中的字符依次转储到链表的各个结点中。
#include <stdio.h> #include <stdlib.h> #include <time.h> struct node //定义结点的结构 { int num; //数据域 struct node * next;//指针域 }; typedef struct node Node;//给结构体命名为Node typedef struct node * link;//给指向结构体的指针命名为link void create_link_head(link * head)//创建链表 { *head = NULL; } void insert_code(link * head,link new_code)//插入头结点 { new_code->next = * head; * head = new_code; } void display_node(link head)//打印头结点 { link tmp; tmp = head; while(tmp != NULL) { printf("num = %d\n",tmp->num); tmp = tmp->next; } } int main() { link head = NULL; //定义头指针 link new_code = NULL;//定义一个新的结点 int i; int num[10]; srand(time(NULL)); for(i = 0;i < 10;i++) { num[i] = rand() % 100; printf("]",num[i]); } printf("\n"); create_link_head(&head); for(i = 0;i <= 9;i++) { new_code = (link)malloc(sizeof(Node)); if(new_code == NULL) { printf("malloc error!\n"); exit(-1); } new_code->num = num[i]; insert_code(&head,new_code); } display_node(head); return 0; }