Data Structure
▪ Data Structure is a way of organizing data in such a way that we
can perform operations on these data in an effective way.
▪ It is a named group of data of different data types which is
stored in a specific way and can be processed as a single unit.
Stack
▪ Dynamic Data Structure :
▪ Stack is a dynamic data structure as it can grow (with increase
in number of elements ) or shrink (with decrease in number of
elements)
▪ Static Data Structure :
▪ Is the one that has fixed size.
Stack
▪ Stack is a linear data structure in which insertion and deletion of elements
can be done, only at the one end that is - Stack’s top.
▪ Stack follows Last-In-First-Out(LIFO) principle i.e., the element which is
inserted last in the stack, will be deleted first from the stack.
▪ The removal of element from a stack is technically called POP operation.
▪ The insertion of element in a stack is technically called PUSH operation.
▪ Examples of stack:
Stack of Pizzas
Stack of Books Stack of Coins
Stack Operations
Push()- Inserting element at the top of stack.
Open end
Push 10 Push 20 Push 30 Push 40 Push 50
50 T
40 T 40
30 T 30 30
20 T 20 20 20
10 T 10 10 10 10
Empty Stack
Pop()- deleting element from the top of stack. Here T stands for Top
T 50 Pop 50 Pop 40 Pop 20
Pop 30 Pop 10 Pop
40 T 40 “Stack-
underflow”
30 30 T 30
20 20 20 T 20
10 10 10 10 T 10
Other Stack terms:
Peek : Getting the most recent value of the stack i.e value at the top.
It is sometimes referred to as inspection.
Overflow: Refer to situation (ERROR) when one tries to push an item
in stack that is full. This situation occurs when the size of the stack is
fixed and cannot grow further.
Underflow : Refers to situation (ERROR) when one tries to pop/delete
an item from an empty stack.
Implementing stack in python
Peek : Use <stack>[top]
Where <stack> is a list; top is an integer having value equal to len<stack>-1
[ex. U=[1,2,3] (len(u)-1=2 (which is the index no. of last element/top element)
Push: Use <stack>.append(<item>)
Where <item> is item being pushed in the stack.
Pop: Use <stack>.pop()
It removes the last value from the stack and returns it.
Implementation of stack
using list in python
Implementing stack in python
Implementing stack in python
[ex. s=[1,2,3]
t= len(s) – 1 = 2
t > =0 s [t] t=t-1
T 3 <== 1
T 3 <== 2 <== 0
T 3 <== 2 <== 1 -1