Question

Simulating a stack of push, pop and peak in C++ using array of 1000.

Simulating a stack of push, pop and peak in C++ using array of 1000.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the c++ code for generic Stack class implementation with push, pop and peak functions:

#include <iostream>

using namespace std;

template <typename T>

class Stack

{

   T *array;

   int stackTop;

   int maxStackSize;

public:

   //default constructor

   Stack()

   

       array = new T[1000];

       stackTop = -1;

       maxStackSize = 1000;

   

   //function to push element to stack

   void push(T input)

   

       stackTop++;

       if (stackTop == maxStackSize)

       

           std::cout << "Stack Overflow!" << std::endl;

           stackTop--;

       

       else

       

           array[stackTop] = input;

       

   

   //function to return top element

   T peak()

   

       if (stackTop == -1)

       

           std::cout << "Stack is empty" << std::endl;

           return -1;

       

       else

       

           return array[stackTop];

       

   

   //function to pop

   void pop()

   

       if (stackTop == -1)

       

           std::cout << "Stack is empty" << std::endl;

       

       else

       

           stackTop--;

       

   

   //function to check is stack is empty

   bool isEmpty()

   

       if (stackTop == -1)

       

           return true;

       

       return false;

   

   //destructor

   ~Stack()

   

       delete[] array;

   

};

//driver function

int main()

{

   Stack<int> s;//object s of type integer Stack

   for (int i = 0; i < 20; i += 2)//push 0, 2, 4, ..., 18 in stack

   

       s.push(i);

   

   while (!s.isEmpty())

   

       cout << s.peak() << endl;

       s.pop();

   

}


Sample output:

T File Edit View Search Terminal Help iunseen@pc]09:04 AM_$ ~/prog/CPP -> ./main EDITORS #include 18 x Cmain.cpp using nam 16

Add a comment
Know the answer?
Add Answer to:
Simulating a stack of push, pop and peak in C++ using array of 1000.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT