/*创建一个带头结点的链表,头部插入法创建*/ #include<stdio.h> #include<stdlib.h> #define DataType char typedef struct node { DataType data; struct node *next; }ListNode,*LinkList; /*创建一个带头结点的链表*/ LinkList createLinkList() { char ch; LinkList temp,head = (ListNode*)malloc(sizeof(ListNode)); head->next = NULL; puts(" 输入链表节点的数值:"); while((ch = getchar()) !=' ') { temp = (ListNode*)malloc(sizeof(ListNode)); if(!temp) exit(0); temp->data = ch; temp->next = head->next; head->next = temp; } return head; } /*在链表的结尾出插入新节点*/ void insertLinkList(LinkList head,DataType item) { LinkList p,temp = (ListNode*)malloc(sizeof(ListNode)); temp->data = item; temp->next = NULL; if(!temp) exit(0); p = head; while(p->next) p = p->next; p->next = temp; } void print(LinkList head) { LinkList p = head->next; while(p) { printf("%c",p->data); p = p->next; } putchar(10); } void destroyLinkList(LinkList head) { LinkList p,q; p = head->next; while(p) { q = p->next; free(p); p = q; head->next = q; } } int main() { char ch; LinkList head; head = createLinkList(); print(head); puts(" 输入要插入的元素值:"); ch = getchar(); getchar(); insertLinkList(head,ch); print(head); destroyLinkList(head); return 0; }