借助于栈结构将一个单链表逆置
借助于栈结构将一个单链表逆置。
输入输出样例:1组
#1
-
样例输入: 5 //链表中有几个元素 1 2 3 4 5 //链表中的元素分别是什么 样例输出: 5 4 3 2 1 //逆置后输出,利用栈结构
#include <stdio.h> #include <stdlib.h> #define max 100 typedef struct node { char data; struct node *next; } Lnode,*Linklist; typedef struct sta { char data[max]; int top; } stack; stack* init() { stack *s=(stack*)malloc(sizeof(stack)); s->top=-1; return s; } int empty(stack *s) { if(s->top==-1) return 1; else return 0; } Linklist creat(int num)//输入数据创建含头结点的单链表 { Lnode *s,*r; int x;int cout=0; Linklist L; L=(Lnode *)malloc(sizeof(Lnode));//需开辟空间否则无法使数据存入进去 L->next=NULL; r=L; while(cout<num) { scanf("%d",&x); s=(Linklist)malloc(sizeof(Lnode)); s->data=x; s->next=NULL; r->next=s; r=s; cout++; } return L; } void push(stack* s,Lnode *x)//入栈 { if(s->top==max-1) return; else { s->top++; s->data[s->top]=x->data; } } //void pop(stack* s,Lnode **x) //{ // // if(empty(s)) return; // else // { // (*x)->data=s->data[s->top]; // s->top--; // } //} int pop(stack* s,int *x)//出栈 { if(empty(s)) return 0; else { *x=s->data[s->top]; s->top--; } return *x; } void result(Linklist L) { Lnode *p,*l;int x; stack *s=init(); p=L->next;//指向第一个结点 l=L; L->next=NULL; while(p)//将链表结点数据入栈 { push(s,p); p=p->next; } while(!empty(s)) { x=pop(s,&x); // l->next=q;//依次将数据点出栈 // l=q;//尾插,实现逆置 printf("%d ",x); } // l->next=NULL; // return L; } int main() { Linklist L; int num; scanf("%d",&num);//输入数据的个数 L=creat(num); result(L); // while(L) // { // L=L->next; // printf("%c ",L->data); // } return 0; }