web123456

Use the stack to achieve inverse of strings

#include <> #include <> #define MAXSIZE 20 //Define a sequential stack typedef struct Node{ char str[MAXSIZE]; int top; }SeqStack; //initialization void InitStack(SeqStack &S) { S.top=-1; } //Judge whether the order stack is empty int StackEmpty(SeqStack &S) { if(S.top==-1) return true; else return false; } //Input the stack int Push(SeqStack &S,char x) { if(S.top==MAXSIZE-1) return false; else { S.top++; S.str[S.top]=x; return true; } } //Open the stack (here we store the value of the top element of the stack in x and return this value) char Pop(SeqStack &S) { char x; if(S.top==-1) printf("Stack empty"); else { x=S.str[S.top]; S.top--; return x; } } int main(){ char str[MAXSIZE]; SeqStack S; int i; printf("The string before the reverse is: \n"); gets(str);//Enter a string InitStack(S); for (i=0;str[i]; i++) { Push(S, str[i]);//Put the elements in the character array into the stack } printf("The reversed string is: \n"); while (!StackEmpty(S)) { putchar(Pop(S));//Output the top element returned by calling the Pop function (existing in x) } printf("\n"); return 0; }