Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

CD3291- DataStructures and Algorithms

Unit-1

Prepared By

R.J.Alice Nineta
AP/IT
STACK ADT
ADT-Abstract Datatype
➔ Mathematical expression that describes how the set
of operation is implemented
➔It is an extension of modular design.

➔A stack is a list that insertion and deletion can be

performed in only one position namely the end of the


list is called top.
➔2 operations on the stack are

1.push-->insert

2.pop---> delete
➔ Stack is also known as LIFO(Last in First OUT)
TOP:
It is a pointer which keep track of the top
element in the stack.

Initially top=-1 when the stack is empty.


STACK ADT
Application of stack is
Recursion
A procedure that can repeat itself definitely is
called recursion.
Implementation:
Stacks can be implemented as
i) Array implementation of stack
ii)Linked List implementation of stack
ARRAY IMPLEMENTATION OF STACK
Top=-1 for an empty stack.
To push an element X on to the stack,increment
the top pointer and insert an item into the stack.
To pop,set the return value of stack and then
decrement the top pointer
The size of the array must be declared first.
A stack can be declared as a structure containing
two objects.
1.An array to hold the elements of the stack.
2.An integer to indicate the position of the current
stack top element within the array.
class Stack:
# Constructor to initialize the stack
def __init__(self, size):
self.arr = [None] * size
self.capacity = size
self.top = -1
Procedure for empty operation:
defisEmpty(self):
returnself.size() == 0
Procedure for stack is full
●defisFull(self):

●returnself.size() == self.capacity
Push:
def push(self, x):
ifself.isFull():
print("Stack Overflow!! Calling exit()…")
exit(1)
print("Inserting", x, "into the stack…")
self.top = self.top + 1
self.arr[self.top] = x
Pop:
def pop(self):
# check for stack underflow
ifself.isEmpty():
print("Stack Underflow!! Calling exit()…")
exit(1)
print("Removing", self.peek(), "from the stack")
#decrease stack size by 1 and (optionally)
return the popped element
top = self.arr[self.top]
self.top = self.top - 1
return top

You might also like