数据结构这门课程中,我首先接触的就是链表.
链表是一种相对简单的数据结构,但是我在编写程序的时候经常运行出错.
为什么?自己对链表的掌握不足.
自己温习了一下课本,写了最基础的链表逆序打印.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char elemtype; typedef struct list { elemtype ch; struct list *next; }*linklist,listnode; linklist creat_list(linklist head) { linklist node,tmp; char temp; head = NULL; /*输入字符以'#'号结束*/ while((temp = getchar())!='#') { node = (linklist)malloc(sizeof(listnode)); node->ch = temp; node->next = head; head = node; } return head; } /*逆序打印链表*/ void print(linklist head) { linklist temp = head; while(temp) { printf("%c ",temp->ch); temp = temp->next; } } int main() { linklist head; head = creat_list(head); print(head); return 0; }
为什么是逆序打印链表呢?
原因是这一段程序
while((temp = getchar())!='#') { node = (linklist)malloc(sizeof(listnode)); node->ch = temp; node->next = head; head = node; }
这一段代码说明了每次加入新的节点,都会讲该节点加入链表的标头.
今天先写这一点.自己正忙着期末考试.静待暑假.....