/*创建一个链表,尾结点插入法*/ #include<stdio.h> #include<stdlib.h> #define DataType char /*节点类型*/ typedef struct node { DataType data; struct node *next; }ListNode,*LinkList; /* *不带头结点 *尾插入法的实现 *从头结点读取的时候,就是按照输入顺序读出的 */ LinkList createLinkList() { DataType ch; LinkList p,head,rear; head = rear = NULL; /*读取元素*/ puts("输入节点的数据:"); while((ch = getchar()) != ' ') { p = (LinkList)malloc(sizeof(ListNode)); if(!p) exit(0); p->data = ch; p->next = NULL; if(NULL== head) head = p; else rear->next = p; rear = p; } return head; } /*在链表尾部插入元素*/ LinkList insertLinkList(LinkList head,DataType item) { LinkList temp,rear = head; while(rear->next) rear = rear->next; temp = (LinkList)malloc(sizeof(ListNode)); if(!temp) exit(0); temp->data = item; temp->next = NULL; rear->next = temp; return head; } /* *从链表中查找元素并删除它 *支持删除相同元素 */ LinkList delLinkList(LinkList head,DataType item) { LinkList q,p = head; while(p) { if(p->data == item) { if(p == head) {head = p->next;free(p);p = head;continue;} q->next = p->next; free(p); p = q->next; continue; } q = p; p = p->next; } return head; } void destroyLinkList(LinkList head) { LinkList p = head; while(head) { p = head->next; free(head); head = p; } } void print(LinkList head) { LinkList p = head; while(p) { printf("%c",p->data); p = p->next; } } int main() { char ch; LinkList p,head; head = createLinkList(); if(NULL == head) printf("The LinkList is empty. "); else print(head); puts(" 输入要插入的元素:"); ch = getchar(); getchar(); head = insertLinkList(head,ch); if(NULL == head) printf("The LinkList is empty. "); else print(head); puts(" 输入您要删除的元素:"); ch = getchar(); getchar(); head = delLinkList(head,ch); if(NULL == head) printf("The LinkList is empty. "); else print(head); destroyLinkList(head); return 0; }