UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
Stacks Implementation and Examples
1. CIS-122 : Data Structures
Lecture- # 2
On Stacks
Conducted by
Syed Muhammad Haroon , SE
Pakistan Institute of Engineering & Applied Sciences
Department of Computer & Information Sciences
2. Outline
• Revision of Lecture # 01
Definition
Representation of Stack
Operations on Stack
• Lecture # 02
Applications of Stack
• Arithmetic Expression
• Recursion : Factorial
• Quick Sort
• Tower of Hanoi
Assignment
• Stack Machines
• Record Management
4. What is a stack?
• Ordered group of homogeneous items.
• Added to and removed from the top of the stack
• LIFO: Last In, First Out.
5. BASIC STACK OPERATIONS
• Initialize the Stack.
• Pop (delete an item)
• Push (insert an item)
• Status(Empty, Full, No of Item, Item at Top)
• Clear the Stack
• Determine Stack Size
6. Representation of Stacks
• Arrays
Fixed Size Stack
Item, top
• Link List
Dynamic Stack
Node: data, link
Stack Header
7. Array Representation of stacks
• To implement a stack, items are inserted and
removed at the same end (called the top)
• To use an array to implement a stack, you need
both the array itself and an integer
The integer tells you either:
• Which location is currently the top of the stack, or
• How many elements are in the stack
7
8. Pushing and popping
• To add (push) an element, either:
Increment top and store the element in stk[top], or
Store the element in stk[count] and increment count
• To remove (pop) an element, either:
Get the element from stk[top] and decrement top, or
Decrement count and get the element in stk[count]
9. Linked-list implementation of stacks
• Since all the action happens at the top of a stack, a singly-linked list
(SLL) is a fine way to implement it
• The header of the list points to the top of the stack
myStack:
44 97 23 17
• Pushing is inserting an element at the front of the list
• Popping is removing an element from the front of the list
9
10. Linked-list implementation details
• With a linked-list representation, overflow will not happen (unless
you exhaust memory, which is another kind of problem)
• Underflow can happen, and should be handled the same way as
for an array implementation
• When a node is popped from a list, and the node references an
object, the reference (the pointer in the node) does not need to be
set to null
Unlike an array implementation, it really is removed--you can no longer
get to it from the linked list
Hence, garbage collection can occur as appropriate
10
12. Building an Arithmetic Expression Evaluator
Infix and Postfix Expressions: Assume 1-digit integer operands and
the binary operators + - * / only
Infix Expression Properties:
Usual precedence and associativity of operators
Parentheses used to subvert precedence
Postfix Expression Properties:
Both operands of binary operators precede operator
Parentheses no longer needed
Infix Expression Equivalent Postfix Expression
3*4+5 34*5+
3*(4+5)/2 345+*2/
(3+4)/(5-2) 34+52-/
7-(2*3+5)*(8-4/2) 723*5+842/-*-
3-2+1 32-1+
13. Building an Arithmetic Expression Evaluator
Assume 1-digit integer operands,
Postfix Expression String Processing the binary operators + - * / only,
and the string to be evaluated is
properly formed
Rules for processing the postfix string:
Starting from the left hand end, inspect each character of the string
1. if it’s an operand – push it on the stack
2. if it’s an operator – remove the top 2 operands from the stack,
perform the indicated operation, and push the result on the stack
An Example: 3*(4+5)/2 345+*2/ 13
Remaining Postfix String int Stack (top) Rule Used
345+*2/ empty
45+*2/ 3 1
5+*2/ 34 1
+*2/ 345 1
*2/ 39 2
2/ 27 2
/ 27 2 1
null 13 2
value of expression at top of stack
14. Building an Arithmetic Expression Evaluator
Infix to Postfix Conversion
Assume 1-digit integer operands,
the binary operators + - * / only,
and the string to be converted is
properly formed
Rules for converting the infix string:
Starting from the left hand end, inspect each character of the string
1. if it’s an operand – append it to the postfix string
2. if it’s a ‘(‘ – push it on the stack
3. if it’s an operator – if the stack is empty, push it on the stack else pop operators o
greater or equal precedence and append them to the postfix string, stopping whe
a ‘(‘ is reached, an operator of lower precedence is reached, or the stack is emp
then push the operator on the stack
4. if it’s a ‘)’ – pop operators off the stack, appending them to the postfix string, until
a ‘(‘ is encountered and pop the ‘(‘ off the stack
5. when the end of the infix string is reached – pop any remaining operators off the
stack and append them to the postfix string
17. Recursion
• A recursive definition is when something is defined partly
in terms of itself
• Here’s the mathematical definition of factorial:
1, if n <= 1
factorial(n) = n * factorial(n – 1) otherwise
• Here’s the programming definition of factorial:
static int factorial(int n) {
if (n <= 1) return 1;
else return n * factorial(n - 1);
}
17
18. Supporting recursion
static int factorial(int n) {
if (n <= 1) return 1;
else return n * factorial(n - 1);
}
• If you call x = factorial(3), this enters the factorial
method with n=3 on the stack
• | factorial calls itself, putting n=2 on the stack
• | | factorial calls itself, putting n=1 on the stack
• | | factorial returns 1
• | factorial has n=2, computes and returns 2*1 = 2
• factorial has n=3, computes and returns 3*2 = 6
18
19. Factorial (animation 1)
• x = factorial(3)
3 is put on stack as n
• static int factorial(int n) { //n=3
int r = 1;
if (n <= 1) returnput on stack with value 1
r is r;
else {
r = n * factorial(n - 1);
return r;
}
}
r=1
All references to r use this r
All references to n use this n n=3
Now we recur with 2...
19
20. Factorial (animation 2)
• r = n * factorial(n - 1);
2 is put on stack as n
• static int factorial(int n) {//n=2
int r = 1;
if (n <= 1) returnput on stack with value 1
r is r;
else {
r = n * factorial(n - 1); Now using this r r=1
return r;
} And this n n=2
}
r=1
n=3
Now we recur with 1...
20
21. Factorial (animation 3)
• r = n * factorial(n - 1);
1 is put on stack as n
• static int factorial(int n) {
r=1
Now using this r
int r = 1;
if (n <= 1) return r; stack with value 1 And
r is put on
n=1
this n
else {
r = n * factorial(n - 1); r=1
return r;
} n=2
}
r=1
Now we pop r and n off the
stack and return 1 as
n=3
factorial(1)
21
22. Factorial (animation 4)
• r = n * factorial(n - 1);
• static int factorial(int n) {
r=1
Now using this r
int r = 1;
if (n <= 1) return r; And
fac=1
n=1
this n
else {
r = n * factorial(n - 1); r=1
return r;
} n=2
}
r=1
Now we pop r and n off the
stack and return 1 as n=3
factorial(1)
22
23. Factorial (animation 5)
• r = n * factorial(n - 1);
• static int factorial(int n) {
int r = 1;
if (n <= 1) return r;
else {
r = n * factorial(n - 1); Now using this r r=1
return r;
} And fac=2
n=2
this n
} 1
r=1
2 * 1 is 2;
Pop r and n;
n=3
Return 2
23
24. Factorial (animation 6)
• x = factorial(3)
• static int factorial(int n) {
int r = 1;
if (n <= 1) return r;
else {
r = n * factorial(n - 1);
return r;
}
} 2
Now using this r r=1
3 * 2 is 6;
Pop r and n;
And fac=6
n=3
this n
Return 6
24
25. Stack frames
• Rather than pop variables off the stack
one at a time, they are usually organized
into stack frames r=1
• Each frame provides a set of variables
n=1
and their values
• This allows variables to be popped off all r=1
at once
n=2
• There are several different ways stack
frames can be implemented r=1
n=3
25
27. Towers of Hanoi
• The Towers of Hanoi is a puzzle made up of three
vertical pegs and several disks that slide on the
pegs
• The disks are of varying size, initially placed on
one peg with the largest disk on the bottom with
increasingly smaller ones on top
• The goal is to move all of the disks from one peg
to another under the following rules:
We can move only one disk at a time
We cannot move a larger disk on top of a smaller one