CodeISM Class 16 (Stack & Queue)
CodeISM Class 16 (Stack & Queue)
Stack
Stack is a linear data structure. The insertion and deletion
happens only at one end. It follows the property of “Last In First
Out”(LIFO)
Syntax for creating a stack
stack<data_type> stack_Name;
Example:
stack<char> st;
stack<double> st;
Functions related to stack: Time Complexity=O(1)
1. push()-> Insert the last element at the back of your stack.
st.push(4);
2. pop() -> Remove the last element from the back.
st.pop();
3. empty()-> return true is the stack is empty()
st.empty(); //True/False
4. size() -> return the number of elements presents in the
stack.
5. top() -> show the top element
cout<<st.top();
Queue
Queue is also a linear data structure in which insertion happens
from one end and deletion happens from another end.
It follows the property of “First In First Out”(FIFO)
Syntax for creating a queue
queue<data_type> queue_Name;
Example:
queue<char> q;
queue<double> q;
Functions related to queue: Time Complexity=O(1)
1. push() -> insert the element at the back.
q.push(4);
q.pop();
I-> Insertion
R-> Removal
Syntax of creating a deque
deque<data_type> deque_Name;
Example
deque<char> dq;
deque<double> dq;
Functions related to deque: Time Complexity=O(1)
1. push_back() -> Insert an element at the back
2. pop_back() -> Remove the last element present at the back
3. push_front() -> Insert an element at the front
4. pop_front() -> Remove the first element present at the front
5. empty() -> return true is the deque is empty()
dq.empty(); // returns True or False
6. size()->return the number of elements presents in the deque.
Note: All these functions for stack, queue and deque have O(1)
constant time complexity
Some Problems
Q.) Balanced Parentheses.
A bracket is considered to be any one of the following characters:
(, ), {, }, [, or ].
Examples:
()-> Balanced
[()]-> Balanced
[((]-> not balanced
[(])-> not balanced
{(})-> not balanced
Solution Approach:
ith element -> if it is (,[,{ -> push in the stack
-> if it is closing bracket ] -> [ , )->(, }-> {
( it should match with the top element in stack)
[()[]]
i=0 -> s[i]= [ -> push in stack
Sol:
string s; // [[
cin>>s;
stack<char> st;
bool balanced=true;
for(int i=0;i<s.length();i++){
if(s[i]=='('||s[i]=='{'||s[i]=='['){
st.push(s[i]);
continue;
}
// a closing bracket encountered....pop one element
from the stack
if(!st.empty()){
char c = st.top();
st.pop();
if((s[i]==')'&&c=='(')||(s[i]=='}'&&c=='{')||(s[i]==']'&&c==
'[')){
// match of s[i] is found
}else{
// c and s[i] are not matching
balanced=false;
break;
}
}else{
balanced=false;
break;
}
}
if(!st.empty()){
balanced=false;
}
if(balanced){
cout<<"Balanced";
}else{
cout<<"Not balanced";
}
https://www.codechef.com/problems/DC206
4,6,5
4,5,6
4,5,7,6
HW:
Try to write code for finding "previous smaller element" for each
element.