问题描述:实现单链表的逆序,如输入1 2 3 4 5 6,则输出6 5 4 3 2 1.
#include<stdio.h>
#include<stdlib.h>
void main(){
struct node {
int data;
struct node *next;
};
struct node *p,*q,*k,*h,*l,*o,*z,*f,*g;
int n,m,b=0;
printf("请输入序列的长度:");
scanf("%d",&m);
printf("请输入序列的值:");
scanf("%d",&n);
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
k=p;
z=(struct node *)malloc(sizeof(struct node));//设置头结点
z->next=p;
while (b<m-1){
scanf("%d",&n);
q=(struct node *)malloc(sizeof(struct node));
q->data=n;
k->next=q;
k=q;
b++;
}
q->next=NULL;
h=p;
printf("您输入的序列为:");
while(h!=NULL){
printf("%d ",h->data);
h=h->next;}
printf("\n");
o=z->next->next;
z->next->next=NULL;
while(o!=NULL){
g=o->next;
o->next=z->next;
z->next=o;
o=g;}
f=z->next;
printf("链表逆序后的序列为:");
while (f!=NULL){
printf("%d ",f->data);
f=f->next;}
printf("\n");}
该程序在Visual C++6.0上运行结果如下: