C Program To Reverse a String using Stack | DS - IProgramX

Q. Write a function that reverses a string of characters. The function should use a stack library (cststack.h) of stack of characters using a static implementation of the stack.



Program

#include <stdio.h>
#include <string.h>
#include "cststack.h"
main()
{
   char str[]="IProgramX";
   printf("%s\n",str);
   int len = strlen(str);
   int i;

   for(i=0;i<len;i++)
        push(str[i]);

   for(i=0;i<len;i++)
      pop();
}

Library Function ( .h file )
NOTE: save file name as ' cststack.h'.

#define max 100
int top,stack[max];
void push(char x)
{
      if(top == max-1){
          printf("stack overflow");
      }  else {
          stack[++top]=x;
      }

}
void pop()
{
      printf("%c",stack[top--]);
}

Output:

IProgramX
XmargorPI

Post a Comment

0 Comments