3. • Stack is a linear data structure.
• Stack have two end one is top and another is bottom.
4. 5 operations
• Push: push element in top of stack
• Pop: pop top element
• size: give number of elements in stack
• top: give top element value
• isempty: say stack is empty or not
5. • Use in-built stack and understand more deeply.
• C++ add library: #include<stack> or #include<bits/stdc++.h>
• Java add library: import java.util.stack
• c++ declaration common way :
(name_of_data_structure) <data-type> variable_name
• stack<int>st => (stack for integer and stack name is st)[s small]
• Java declaration
Stack<Integer>st = new Stack<>() [Stack => S capital]
6. Operation 1: Push O(1)
Push: element 1
You can push element only top of the stack
Push: element 2 Push: element 3
7.
8. Operation 2: pop O(1)
• You can pop only top element
pop pop pop
C++ and java both => stack_name.pop() [no need parameter]
9. Operation 3: size O(1)
• This operation is use for find how many elements present in stack
Stack size is 4 because 4 elements present in stack
Initially size=0
When you push element then apply size++ and pop
element then apply size—
Size operation return size value directly in O(1)
Stack_name.size() => [c++/java]
10. Operation 4: top O(1)
• return top element value
Here top element is 4
Stack_name.top() => c++
Stack_name.peek() => java
11. Operation 5: isempty O(1)
• Check stack is empty or not if stack is empty then return true
otherwise return false
Here stack is not empty so return false
Stack_name.isempty()
12. Operation 6: search (only in java)
Stack name : st
st.search(5) => return 2 (position 2 see in diagram)
st.search(6) => return -1 (6 is not present in stack)
16. • We can implementation stack using linked list or array-list
• we can see using linked list (better space complexity)
• Using linked list or array-list we can perform all operation in O(1)
• Make class node
18. Void remove()
{
if(size>0)
{
head=head.next;
size--;
}
}
Operation 3:size
Operation 2:pop
Operation 5:isempty
bool isempty()
{
return size==0;
}
int size()
{
return size;
}
Operation 4:top
int top()
{
return head.data
}
Note: this function return type is
you stack data-type
head.data, head.val depende you
node class
In java use head.next , head.data
In c++ use head->next, head->data
20. • In this topic we can find out next greater element left and right side
• Suppose array [100,40,20,50,1,60,120] find next greater element of 1 and
60
• See left side of 1 [50,20,40,100] pick first greater element (>1) => 50
• See right side of 1 [60,120] pick first greater element (>1) => 60
• See left side of 60 [1,50,20,40,100] pick first greater element (>1) => 100
• See right side of 1 [120] pick first greater element (>1) => 120
• how to find for 120 and 100 (120 have no greater element left and right
and 100 have greater element only right side)
• In this case we can assume -1 index present in n index also present (n is
array size) both have infinity value