#include<stdio.h> #include<stdlib.h> typedef struct node { char data; struct node* next; }*Lnode,Node; Lnode AppendNode(Lnode head);//创建链表节点 void printNode(Lnode head);//遍历打印链表 void destroyList(Lnode head);//释放链表 int main() { char c; Lnode head = NULL; head = (Lnode)malloc(sizeof(Node)); head->next = NULL; printf("你想创建链表吗?(Y/N)"); scanf_s("%c", &c); while (c == ‘y‘ || c==‘Y‘) { getchar(); head = AppendNode(head); printf("你想创建链表节点吗?(Y/N)"); scanf_s("%c", &c); } printNode(head); destroyList(head); } Lnode AppendNode(Lnode head) { Lnode p = NULL; Lnode pr = head; p = (Lnode)malloc(sizeof(Node)); if(p==NULL)//申请内存失败 { printf("申请内存失败!"); exit(0); } if (pr->next == NULL)//链表为空时,直接添加到头节点之后 { pr->next = p; p->next = NULL; } else//链表不为空时,添加到链表最后 { while (pr->next != NULL) { pr = pr->next; } pr->next = p; p->next = NULL; } printf("输入节点的数据:"); scanf_s("%c",&(p->data)); getchar(); return head; } void printNode(Lnode head) { printf("链表中的数据为:"); Lnode p = head->next; if (p == NULL) { printf("这是一个空链表"); } else { while (p != NULL) { printf("%c",p->data); p = p->next; } } } void destroyList(struct node* head) { struct node* pr = head; struct node* p = NULL; if (pr!= NULL) { p = pr; pr = pr->next; free(p); } }
原文:https://www.cnblogs.com/Oats/p/12736779.html