#include <stdio.h> #include <ctype.h> #include <stdlib.h> typedef struct List { char data; struct List *next; }List; //创建单链表 List *list_create(void) { struct List *head,*tail,*p; char e; head=(List *)malloc(sizeof(List)); //申请头结点 tail=head; printf("c List Create,input numbers(end of 0):"); scanf("%c",&e); while(e-0x30) { p=(List *)malloc(sizeof(List)); //申请新结点 p->data=e; tail->next=p; //将新结点链接至前一结点之后 tail=p; scanf("%c",&e); } tail->next=NULL; //最后结点指空 return head; } //链表逆置 List *list_reverse(List *head) { List *p,*q,*r; p=head; q=p->next; while(q!=NULL) //判断是否还有结点 { r=q->next; //保留未逆转数据 q->next=p; //实现逆转,指向上一个结点 p=q; //以逆转结点 q=r; //需要逆转的结点 } head->next=NULL; //最后结点指空 head=p; return head; } //计算链表长度 int list_len(List *head) { List *p; int len = 0; p = head->next; while (p != NULL) { len++; p = p->next;//指向下一个结点 } printf(" %d ",len); return len; } //在index位置增加结点,数据为date List *list_addnote(List *head, int index, char date) { List *p,*pNew,*q; int i = 0; p = head; while (i < index) //查找index位置 { p = p->next; i++; } pNew = (List *)malloc(sizeof(List));//申请空间 pNew->data = date; q = p->next; //保存下一个结点 p->next = pNew; //插入 pNew->next = q; //将保存的结点链接置插入结点之后 return head; } //删除值为date的结点 List *list_delnote(List *head, char date) { List *p,*per; //per为前驱结点 per = head; p = head->next; while (p->data != date) //查找结点 { per = p; p = p->next; } per->next = p->next; //前驱结点指向被删除的下一个 free(p); return head; } void main(void) { struct List *head,*p; head=list_create(); list_addnote(head,2,'x'); list_delnote(head,'a'); printf(" "); for(p=head->next;p;p=p->next) printf("--%c--",p->data); head=list_reverse(head); printf(" "); for(p=head;p->next;p=p->next) printf("--%c--",p->data); list_len(head); }