C 语言 链表的创建与打印
生活随笔
收集整理的這篇文章主要介紹了
C 语言 链表的创建与打印
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C 語言 鏈表的創(chuàng)建與打印
/* 包含的頭文件 */#include <stdio.h>#include <stdlib.h>/* 定義一個表示鏈表的結(jié)構(gòu)體指針 */struct list {int id; /* 標識這個元素方便查找 */char data[20]; /* 鏈表中包含的元素 */struct list *next; /* 指向下一個鏈表的指針 */};/* 定義一個鏈表頭部 */static struct list *list_head = NULL;/* 為了保證每一個鏈表元素的id不同,特意把id定義成一個全局靜態(tài)變量 */static int list_id = 0;/** 將指定元素插入到聊表尾部* head : 表示要插入元素的鏈表的頭部的地址* list : 表示要插入到鏈表中的元素*/static void list_add(struct list **head, struct list *list){struct list *temp;/* 判斷鏈表是否為空 */if(NULL == *head){/* 為空 */*head = list;(*head)->next = NULL;}else{/* 不為空 */temp = *head;while(temp){if(NULL == temp->next){temp->next = list;list->next = NULL;}temp = temp->next;}}}/** 遍歷一個鏈表,打印鏈表中每個元素所包含的數(shù)據(jù)* head : 表示要遍歷的鏈表的頭部的指針*/static void list_print(struct list **head){ struct list *temp;temp = *head;printf("list information :\n");while(temp){printf("\tlist %d : %s\n", temp->id, temp->data);temp = temp->next;}}/* 主函數(shù),程序的入口 */int main(int argc, char *argv[]){int i = 0;struct list *lists = NULL;/* 分配10個元素 */lists = malloc(sizeof(struct list) * 10);if(NULL == lists){printf("malloc error!\n");return -1;}/* 將分配的10個元素依次填充數(shù)據(jù)并加入到鏈表當中 */for(i = 0; i < 10; i++){lists[i].id = list_id++;sprintf(lists[i].data, "TECH-PRO - %d", i);list_add(&list_head, &lists[i]);}/* 遍歷鏈表,把鏈表中每個元素的信息都打印出來 */list_print(&list_head);return 0;}posted on 2018-07-29 20:59 luoganttcc 閱讀(...) 評論(...) 編輯 收藏
總結(jié)
以上是生活随笔為你收集整理的C 语言 链表的创建与打印的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 链表学习(一)静态链表的构造
- 下一篇: python 读取txt