Stacks are a type of container  designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.

Main Stack Operations:


  • push (object): inserts an element.
  • pop (): removes and returns the last inserted element.
  • top(): returns the last element without removing it.
  • size(): returns the number of elements stored.
  • isEmpty(): returns a Boolean value indicating whether o elements are stored.

 

Capture.PNG

#include <iostream>
#include <stack>
using namespace std;

int main()
{
 stack <int> s;
 s.push(3);
 s.push(5);
 s.push(8);

 for (stack <int> temp = s; !temp.empty(); temp.pop())
      cout << temp.top() << endl;

 return 0;

Super Reduce String Problem using stacks

#include <iostream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

int main()
{
   string word;
   stack <char> s;
   stack <char> temp;
   cin >> word;

   for (int i = 0; i < word.length(); i++)
   {
     if (s.empty() || s.top() != word[i])
         s.push(word[i]);
     else
         s.pop();
   }
   if (s.empty())
      cout << "Empty String" << endl;
   else
   {
     while (!s.empty())
     {
       temp.push(s.top());
       s.pop();
     }
     while (!temp.empty())
     {
      cout << temp.top();
      temp.pop();
     }
   }
 return 0;
}

Queue 

  • Insertions and deletions follow the first-in first-out (FIFO) scheme.
  • Insertions are at the rear of the queue and removals are at the front of the queue.

Main Queue Operations: 

  • enqueue (0): insert element 0 at the end of the queue.
  • dequeue ()  : removes and returns the element at the front of the queue.
  • front (): returns the element at the front without removing it.
  • size(): returns the number of elements stored.
  • isEmpty(): returns a Boolean value indicating whether no elements are stored.

Capture.PNG

 

 

 

 

 

 

 

 

Advertisements