Posts

Showing posts with the label stack

Stack using Queues

#include<bits/stdc++.h> using namespace std; class Q { stack<int> s1,s2; public :void enque(int a) { s1.push(a); } public:int deque() { int j=-1; while(s1.size()<=1) { int a= s1.top(); s1.pop(); s2.push(a); } if(s1.size()==1) { j=s1.top(); s1.pop(); } while(!s2.empty()) { int a= s1.top(); s1.pop(); s2.push(a); } return j; } }; int main() { Q q1; int r=0; while(r!=3) { cout<<"1. Enque"<<endl; cout<<"2.Deque"<<endl; cout<<"3. exit"<<endl; cin>>r; if(r==1) {int e; cout<<"Enter an element to insert in queue"; cin>>e; q1.enque(e); } else if(r==2) { cout<<q1.deque()<<endl; } } }

Get minimum of stack in Reasonable time

// what if a product based  company asks that they want the minimum of stack in resonalble time.. // if you knew this program congrats... you got job in product based company #include<iostream> #include<stack> using namespace std; void push(int a); bool isFull(int n); bool isEmpty(); int pop(); int getMin(); stack<int> s; int main(){ int t; cin>>t; while(t--){ int n,a; cin>>n; while(!isEmpty()){     pop(); } while(!isFull(n)){ cin>>a; push(a); } cout<<getMin()<<endl; } } /*This is a function problem.You only need to complete the function given below*/ /*Complete the function(s) below*/ void push(int a) {      s.push(a); } bool isFull(int n) {     return (s.size()==n); } bool isEmpty() {return s.empty();     } int pop() {     int a=s.top();     s.pop();     return a ;     } in...

Stack - print bracket number

/ * example 2 (0+1)*0(0+1)*0(0+1)* (1*0)*1* o/p 1 1 2 2 3 3  1 1  Example: Input: 3 (a+(b*c))+(d/e) ((())(())) ((((() Output: 1 2 2 1 3 3 1 2 3 3 2 4 5 5 4 1 1 2 3 4 5 5 */ #include<bits/stdc++.h> using namespace std; int main()  { int t; cin>>t; while(t--) {     string s;     stack <int> st;     int c=0; // we maintain the count of open brackets     cin>>s;     for(int i=0;i<s.length();i++)     {         if(s[i]=='(')         {c++;         cout<<c<<" ";         st.push(c);         }         if(s[i]==')')         {             cout<<st.top()<<" ";             st.pop();         } ...

Infix to postfix conversion using stack

//  We genrally read infixes as a+b but computers need things in postfix i.e  +ab  with pirority in //symbols , // if you want to know the concept   https://codeburst.io/conversion-of-infix-expression-to-postfix-expression-using-stack-data-structure-3faf9c212ab8 // if you already know the concept then head on to this program below :) #include<bits/stdc++.h> using namespace std; int priority(char c) {     if((c=='^'))     {         return 3;     }     else if(c=='*'||c=='/')     {         return 2;           }     else if(c=='+'||c=='-')     {         return 1;     }     else     {         return -1;     } } void infixtopostfix(string s) { string os; stack<char> st; int i; char c; for(i=0;i<s.length();i++) ...