You are on page 1of 14

CS250 - Data Structures and

Algorithm
BESE-2A/B

Lecture 08
Aasma Zahid
Stacks

9/28/2012 DSA - Fall 2012 - SEECS, NUST 2


Stack
• A linear data structure that is used for storing
and retrieval of data

• Storing and retrieval principle


– LAST IN FIRST OUT (LIFO)

• Example
– Which is the first coin to pick up
from the stack of gold coins?
9/28/2012 DSA - Fall 2012 - SEECS, NUST 3
Last in First Out

E top
top
D top D D
C top C C C
B top B B B B
A A A A A
A top

9/28/2012 DSA - Fall 2012 - SEECS, NUST 4


Stack Attributes
• Size
– The number of elements on the stack

• Top
– Points to the top most element on the stack. This
refers to NULL if stack is empty or size = 0

9/28/2012 DSA - Fall 2012 - SEECS, NUST 5


Stack Operations
• Primarily two operations performed on one
end only
• Push
– Add an item on the
top of stack

• Pop
– Remove an item at
the top of stack
9/28/2012 DSA - Fall 2012 - SEECS, NUST 6
Stack Operations
• Push(element) – insert the element on the
top of the stack
• Pop() – removes the top most element
• Peek() – return the top most element without
removing it
• isEmpty() – check to see if stack is empty
• isFull() – check to see if stack is full
• Clear() – clear the stack
9/28/2012 DSA - Fall 2012 - SEECS, NUST 7
Stack Operations

9/28/2012 DSA - Fall 2012 - SEECS, NUST 8


Applications
• Real life
– Stack of trays in cafeteria
– Piles of books in library

• Computer Science
– Program Execution Stack
– Evaluating Expressions and Syntax Parsing
– Convert decimal to binary
– Tower of Hanoi
– Undo operations
9/28/2012 DSA - Fall 2012 - SEECS, NUST 9
Choice of Implementation
• Array based Stack
– Maximum stack size is known ahead of time
• Linked List based Stack
– Maximum stack size unknown

9/28/2012 DSA - Fall 2012 - SEECS, NUST 10


Array Based Stack
• When using an array to implement a stack
– The array's first element should represent the
bottom of the stack
– The last occupied location in the array represents
the stack's top
• This avoids shifting of elements of the array
when we push or remove elements from stack

9/28/2012 DSA - Fall 2012 - SEECS, NUST 11


Array Based Stack
• Allocate an array of some size (pre-defined)
– Maximum N elements in stack
• Bottom stack element stored at element 0
• last index in the array is the top
• Increment top when one element is pushed,
decrement after pop

9/28/2012 DSA - Fall 2012 - SEECS, NUST 12


Array Based Stack Operations
int stack[size]; Int Pop() {
int top = -1; int element = -1;
if(!isEmpty()){
void Push(int element){ element = stack[top];
if(!isFull()){ stack[top--]=-1;
stack[++top] = element; }
} return element;
} }

bool isFull(){ bool isEmpty(){


return top>size-1; return top<0;
} }

9/28/2012 DSA - Fall 2012 - SEECS, NUST 13


Questions?

9/28/2012 DSA - Fall 2012 - SEECS, NUST 14

You might also like