#include<stdio.h> #include<stdlib.h> #define NUM 10//逆序建立的节点数目 struct chain { int value; struct chain *next; }; struct chain *create() //创建链表,当输入不是int型数据时结束 { struct chain *head,*tail,*p; int x; head = tail = NULL; while(scanf("%d",&x)==1) //成功输入数据的条件; { p=(structchain*)malloc(sizeof(structchain)); //分配动态内存 p->value=x; p->next=NULL; if(head==NULL) head = tail = p; //头结点head数据域有数据 else { tail->next=p; tail=tail->next; } } return head; } struct chain *reverse_create() //逆序建立链表,在L和L->next之间逆序插入链表 { int n=NUM; struct chain *L,*p; L=(struct chain*)malloc (sizeof(structchain)); L->next=NULL; for(inti=n; i>0; i--) { intd=0; p=(structchain*)malloc (sizeof(structchain)); scanf("%d",&d); p->value=d; p->next=L->next; L->next=p; } return L->next; //返回L->next是因为L节点数据域不存在 } struct chain * reverse(structchain*head) //逆序链表 { struct chain* p,*q,*t; q=p=(struct chain*) malloc(sizeof(structchain)); p=head; q=p->next; t=NULL; while(q) { t=q->next; q->next=p; p=q; q=t; } head->next=NULL; //while执行完后,未转换之前链表的head->next没变,还是指向第二个节点,while执行完后,未转换之前链表的头结点变成尾节点,因此要令其指针域为NULL。 head=p; //把原来的尾节点作为头结点 return head; } struct chain *inlink(struct chain*head,int a,intb) //把b插在a之前 { struct chain *p,*q,*s; s = (struct chain *)malloc(sizeof(structchain)); s->value=b; if(head==NULL) { head = s; head->next = NULL; } if(head->value == a) { s->next=head; head = s; } else { p=head; while((p->value!=a)&&(p->next!=NULL)) { q=p; p=p->next; } if(p->value== a) { q->next = s; s->next = p; } else { p->next=s; s->next=NULL; } } return (head); } struct chain *dellink(struct chain*head,int a) //int a代表要删除的节点 { struct chain *q,*p; if(head == NULL) printf("链表为空,无法删除\n"); else if(head->value== a) { p = head; head = head->next; } else { p=head; while((p->value!=a)&&(p->next!=NULL)) { q=p; p=p->next; } if(p->value!= a) printf("链表不存在此节点!\n"); else { q->next = p->next; free(p); } } return (head); } void reverse_output(struct chain*h) //用递归实现链表的逆序输出 { if(h!=NULL) { reverse_output(h->next); printf("%d",h->value); } } void main() { struct chain *p,*q,*p1; q=reverse_create(); //链表的创建; //q=inlink(create(),3,1); //链表的插入; //q=dellink(create(),2); //链表的删除; //p1=inverse(q); reverse_output(q); }