Trivial C, C++ Programs.

Stacks Using Arrays (Static) in C++



This is a general implementation of the stack data structure in C++. I’ve made it a ‘menu-driven’ program, for all you menu-loving whores. Nobody cares if it is rendered unreadable. Also, I’ve skipped bound checks in this program, so remember to sanitize your inputs or you may get sucked into a vortex.

Also, since I’m such a lazy bitch, I didn’t bother with issues relating to scope of the data structure – I made it global for convenience. Take this code, and don’t bitch about it.

 
#include<iostream.h>
 
int *Stack, top=-1, maxSize;
 
void createStack();
void push ();
void pop();
void dispStack();
 
int main()
{
  int choice=0, elem;
  while(choice!=5)
    {
      cout<<"\n\n Enter a choice :"
      <<"\n 1. Create a new empty stack"
      <<"\n 2. Push an element into stack"
      <<"\n 3. Pop an element from stack"
      <<"\n 4. Display the stack"
      <<"\n 5. Exit.\n\n";
      cin>>choice;
      switch (choice)
	{
	case 1:
	  createStack();
	  break;
	case 2:
	  push();
	  break;
	case 3:
	  pop();
	  break;
	case 4:
	  dispStack();
	  break;
	case 5:
	  exit(0);
	  break;
	default:
	  cout<<"\n Invalid choice.";
	  break;
	}
    }
}
 
void createStack()
{
  cout<<"\n Enter maximum size for stack : ";
  cin>>maxSize;
  Stack = new int[maxSize];
}
 
void push()
{
  if (top>=(maxSize-1))
    {
      cout<<"\n Overflow! Element cannot be pushed.";
    }
  else
    {
      top++;
      cout<<"\n Enter element to be pushed into stack : ";
      cin>>Stack[top];
    }
}
 
void pop()
{
  if (top<0)
    {
      cout<<"\n Underflow! Stack is empty, so no element can be popped.";
    }
  else
    {
      cout<<"\n The element that was popped : "<<Stack[top--];
    }
}
 
void dispStack()
{
  if (top<0)
    {
      cout<<"\n Stack is empty, no elements to display.";
    }
  else
    {
      cout<<"\n The stack is : ";
      for (int i=top;i>=0;i--)
	{
	  cout<<"\n"<<Stack[i];
	}
    }
}

1 Comment to Stacks Using Arrays (Static) in C++

  1. K.K's Gravatar K.K
    July 12, 2010 at 23:16 | Permalink

    NYCE PROGRAM

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">