10 - Lec06 - Stacks-2 PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Data Structures and Algorithms

Stacks
Sidra Malik
sidra.malik@ciitlahore.edu.pk
Stacks
• A stack is a list in which insertion and deletion take place at
the same end
– This end is called top
– The other end is called bottom

• Stacks are known as LIFO (Last In, First Out) lists.


– The last element inserted will be the first to be retrieved
• E.g. a stack of Plates, books, boxes etc.
TOP OF THE STACK TOP OF THE STACK

Data Structures and Algorithms-Sidra Malik 2


Stacks…
Insertion and deletion

Data Structures and Algorithms-Sidra Malik 3


Stacks…
Operation On Stack
• Creating a stack
• Checking stack---- either empty or full
• Insert (PUSH) an element in the stack
• Delete (POP) an element from the stack
• Access the top element
• Display the elements of stack

Data Structures and Algorithms-Sidra Malik 4


Stacks…
Push and Pop
• Primary operations: Push and Pop
Push
– Add an element to the top of the stack.
Pop
– Remove the element at the top of the stack.

Data Structures and Algorithms-Sidra Malik 5


Stack-Related Terms
Top
– A pointer that points the top element in the stack.
Stack Underflow
– When there is no element in the stack, the status of stack is
known as stack underflow.
Stack Overflow
– When the stack contains equal number of elements as per its
capacity and no more elements can be added, the status of
stack is known as stack overflow
– The condition resulting from trying to push an element onto a
full stack

Data Structures and Algorithms-Sidra Malik 6


Stack Implementation
• Implementation can be done in two ways
– Static implementation
– Dynamic Implementation
Static Implementation
– Stacks have fixed size, and are implemented as arrays
– It is also inefficient for utilization of memory
Dynamic Implementation
– Stack grow in size as needed, and implemented as linked lists
– Dynamic Implementation is done through pointers
– The memory is efficiently utilize with Dynamic Implementations

Data Structures and Algorithms-Sidra Malik 7


Stack Implementations
Array-based

Linked-list-based

Data Structures and Algorithms-Sidra Malik 8


Static/Array Implementation of Stacks
Elements are stored in contiguous cells of an array.
New elements can be inserted to the top of the list.

top First Element


Second Element
List
Last Element

Empty
maxlength

Data Structures and Algorithms-Sidra Malik 9


Array Implementation of Stacks

Data Structures and Algorithms-Sidra Malik 10


Array Implementation of Stacks…
Stack Definition
struct STACK{
int count; /* keeps the number of elements in
the stack */
int top; /* indicates the location of the top of
the stack*/
int items[STACKSIZE]; /*array to store the
stack elements*/
}

Data Structures and Algorithms-Sidra Malik 11


Array Implementation of Stacks…
Stack Initialisation
• initialize the stack by assigning -1 to the top
pointer to indicate that the array based stack
is empty (initialized) as follows:
• You can write following lines in the main
program:
:
STACK s;
s.top = -1;
:

Data Structures and Algorithms-Sidra Malik 12


Array Implementation of Stacks…
Stack Initialisation
• Alternatively you can use the following
function:
void StackInitialize(STACK *Sptr)
{
Sptr->top=-1;
}

Data Structures and Algorithms-Sidra Malik 13


Array Implementation of Stacks…
Push Operation
Push an item onto the top of the stack (insert an item)

Data Structures and Algorithms-Sidra Malik 14


Array Implementation of Stacks…
Void push (Stack *, type newItem)
• Function: Adds newItem to the top of the
stack.
• Preconditions: Stack has been initialized and is
not full.
• Postconditions: newItem is at the top of the
stack.

Data Structures and Algorithms-Sidra Malik 15


Array Implementation of Stacks…
Void push (Stack *, type newItem)
void push(STACK *Sptr, int ps) /*pushes ps into stack*/
{
if(Sptr->top == STACKSIZE-1){
printf("Stack is full\n");
return; /*return back to main function*/
}
else {
Sptr->top++;
Sptr->items[Sptr->top]= ps;
Sptr->count++;
}
}

Data Structures and Algorithms-Sidra Malik 16


Array Implementation of Stacks…
Pop operation
• Pop an item off the top of the stack (delete an
item)

Data Structures and Algorithms-Sidra Malik 17


Array Implementation of Stacks…
type pop (STACK *)
• Function: Removes topItem from stack and
returns with topItem
• Preconditions: Stack has been initialized and is
not empty.
• Postconditions: Top element has been
removed from stack and the function returns
with the top element.

Data Structures and Algorithms-Sidra Malik 18


Array Implementation of Stacks…
Type pop(STACK *Sptr)
int pop(STACK *Sptr)
{
int pp;
if(Sptr->top == -1){
printf("Stack is empty\n");
return -1; /*exit from the function*/
}
else {
pp = Sptr->items[Sptr->top];
Sptr->top--;
Sptr->count--;
return pp;
}
}

Data Structures and Algorithms-Sidra Malik 19


Dynamic Implementation of Stacks

• As we know that dynamic stack is implemented using linked-


list.
• In dynamic implementation stack can expand or shrink with
each PUSH or POP operation.
• PUSH and POP operate only on the first/top cell on the list.

Top
x y z NULL

Data Structures and Algorithms-Sidra Malik 20


Array Implementation of Stacks…
Stack Definition
typedef struct stack {
int data;
struct stack *next;
} STACK;

• corresponds not to the entire stack structure, but to a single


node
• identical to a typical singly linked list node

Data Structures and Algorithms-Sidra Malik 21


Linked-list-based Stacks

Data Structures and Algorithms-Sidra Malik 22


Stack applications
• “Back” button of Web Browser
– History of visited web pages is pushed onto the stack and
popped when “back” button is clicked

• “Undo” functionality of a text editor

• Reversing the order of elements in an array

• Saving local variables when one function calls another, and


this one calls another, and so on.

Data Structures and Algorithms-Sidra Malik 23


Array-vs Linked-list-based
Stack Implementations
• Array-based implementation is simple but:
– The size of the stack must be determined when
a stack object is declared.
– Space is wasted if we use less elements.
– We cannot "enqueue" more elements than the
array can hold.
• Linked-list-based implementation alleviates
these problems but time requirements
might increase.
Data Structures and Algorithms-Sidra Malik 24
Algebraic Expression
• An algebraic expression is a legal combination of operands and
the operators.
• Operand is the quantity (unit of data) on which a mathematical
operation is performed.
• Operand may be a variable like x, y, z or a constant like 5, 4,0,9,1
etc.
• Operator is a symbol which signifies a mathematical or logical
operation between the operands. Example of familiar operators
include +,-,*, /, ^
• Considering these definitions of operands and operators now we
can write an example of expression as x+y*z.

Data Structures and Algorithms-Sidra Malik 25


Infix, Postfix and Prefix Expressions
• INFIX: From our schools times we have been familiar with the
expressions in which operands surround the operator, e.g.
x+y, 6*3 etc this way of writing the Expressions is called infix
notation.

• POSTFIX: Postfix notation are also Known as Reverse Polish


Notation (RPN). They are different from the infix and prefix
notations in the sense that in the postfix notation, operator
comes after the operands, e.g. xy+, xyz+* etc.

• PREFIX: Prefix notation also Known as Polish notation.In the


prefix notation, as the name only suggests, operator comes
before the operands, e.g. +xy, *+xyz etc.

Data Structures and Algorithms-Sidra Malik 26


Operator Priorities
• How do you figure out the operands of an operator?
–a+b*c
–a*b+c/d
• This is done by assigning operator priorities.
– priority(*) = priority(/) > priority(+) = priority(-)
• When an operand lies between two operators,
the operand associates with the operator that
has higher priority.

Data Structures and Algorithms-Sidra Malik 27


Tie Breaker
• When an operand lies between two operators
that have the same priority, the operand
associates with the operator on the left.
–a+b-c
–a*b/c/d

Data Structures and Algorithms-Sidra Malik 28


When are PREFIX and POSTFIX used?

• To our surprise INFIX notations are not as simple as they seem


specially while evaluating them.
• To evaluate an infix expression we need to consider Operators’ Priority
and Associative property
– For example expression 3+5*4 evaluate to 32 i.e. (3+5)*4
or to 23 i.e. 3+(5*4).

• To solve this problem Precedence or Priority of the operators


were defined. An operator with higher precedence is applied
before an operator with lower precedence.

Data Structures and Algorithms-Sidra Malik 29


Infix Expression Is Hard To Parse
• Need operator priorities, tie breaker, and
delimiters.
• This makes computer evaluation more difficult
than is necessary.
• Postfix and prefix expression forms do not rely
on operator priorities, a tie breaker, or
delimiters.
• So it is easier to evaluate expressions that are in
these forms.
Data Structures and Algorithms-Sidra Malik 30
Advantage over INFIX

• Both prefix and postfix notations have an advantage over infix


that while evaluating an expression in prefix or postfix form
we need not consider the Priority and Associative property
(order of brackets).
– E.g. x/y*z becomes */xyz in prefix and xy/z* in
postfix. Both prefix and postfix notations make
Expression Evaluation a lot easier.

Data Structures and Algorithms-Sidra Malik 31


Examples of infix to prefix and post fix
Infix PostFix Prefix

A+B AB+ +AB

(A+B) * (C + D) AB+CD+* *+AB+CD

A-B/(C*D^E) ABCDE^*/-
ABCDE^*/- -A/B*C^DE

Data Structures and Algorithms-Sidra Malik 32


Example: postfix expressions

• Postfix notation is another way of writing arithmetic


expressions.

• In postfix notation, the operator is written after the two


operands.
infix: 2+5 postfix: 2 5 +
• Expressions are evaluated from left to right.

• Precedence rules and parentheses are never needed!!

Data Structures and Algorithms-Sidra Malik 33


Algorithm for Infix to Postfix
1) Examine the next element in the input.
2) If it is operand, output it.
3) If it is opening parenthesis, push it on stack.
4) If it is an operator, then
i) If stack is empty, push operator on stack.
ii) If the top of stack is opening parenthesis, push operator on stack
iii) If it has higher priority than the top of stack, push operator on stack.
iv) Else pop the operator from the stack and output it, repeat step 4

5) If it is a closing parenthesis, pop operators from stack and output them


until an opening parenthesis is encountered. pop and discard the opening
parenthesis.
6) If there is more input go to step 1
7) If there is no more input, pop the remaining operators to output.

Data Structures and Algorithms-Sidra Malik 34


Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form,
Expression Stack Output
2 Empty 2
* * 2
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(
/(-- 23*2
1 /(
/(-- 23*21
) / 23*21
23*21--
+ + 23*21
23*21--/
5 + 23*21
23*21--/5
* +* 23*21-
23*21-/53
3 +* 23*21-
23*21-/53
Empty 23*21-/53*+
23*21-
Data Structures and Algorithms-Sidra Malik 35
So, the Postfix Expression is 23*21-/53*+
Example
• 3+4*5/6

• ( 5 + 6) * 9 +10

• (300+23)*(43-21)/(84+7)

• (4+8)*(6-5)/((3-2)*(2+2))

Data Structures and Algorithms-Sidra Malik 36


Example
• 3+4*5/6
345*6/+
• ( 5 + 6) * 9 +10
5 6 + 9 * 10 +
• (300+23)*(43-21)/(84+7)
300 23 + 43 21 - * 84 7 + /
• (4+8)*(6-5)/((3-2)*(2+2))
48+65-*32–22+*/

Data Structures and Algorithms-Sidra Malik 37


Evaluation a postfix expression
• Each operator in a postfix string refers to the previous
two operands in the string.
• Suppose that each time we read an operand we push it
into a stack. When we reach an operator, its operands
will then be top two elements on the stack
• We can then pop these two elements, perform the
indicated operation on them, and push the result on the
stack.
• So that it will be available for use as an operand of the
next operator.

Data Structures and Algorithms-Sidra Malik 38


Evaluating Postfix Expressions
"By hand" (Underlining technique):
1. Scan the expression from left to right to find an operator.
2. Locate ("underline") the last two preceding operands
and combine them using this operator.
3. Repeat until the end of the expression is reached.

Example:
2 3 4 + 5 6 - - *
→ 2 3 4 + 5 6 - - *
→ 2 7 5 6 - - *
→ 2 7 5 6 - - *
→ 2 7 -1 - *
→ 2 7 -1 - * → 2 8 * → 2 8 * → 16
Data Structures and Algorithms-Sidra Malik 39
Example: Postfix Expressions

Expressions are evaluated from left to right.

Data Structures and Algorithms-Sidra Malik 40


Evaluating Postfix Expressions through
Stacks
By using a stack algorithm
1. Initialize an empty stack
2. Repeat the following until the end of the
expression is encountered
a) Get the next token (const, var, operator) in the
expression
b) Operand – push onto stack Note: if only 1 value on stack,
Operator – do the following this is an invalid RPN
i. Pop 2 values from stack expression
ii. Apply operator to the two values
iii. Push resulting value back onto stack
3. When end of expression encountered, value of
expression is the (only) number left in stack
Data Structures and Algorithms-Sidra Malik 41
Postfix expressions:
Algorithm using stacks

Data Structures and Algorithms-Sidra Malik 42


Algorithm for Infix to Prefix
Step 1. Push “)” onto STACK, and add “(“ to end of the infix expression
Step 2. Scan infix expression from right to left and repeat step 3 to 6 for each
element until the STACK is empty
Step 3. If an operand is encountered add it to output
Step 4. If a right parenthesis is encountered push it onto STACK
Step 5. If an operator is encountered then:
a. Repeatedly pop from STACK and add to output each operator (on the top
of STACK) which has same or higher precedence than the operator.
b. Add operator to STACK
Step 6. If left parenthesis is encountered then
a. Repeatedly pop from the STACK and add to B (each operator on top of
stack until a left parenthesis is encountered)
b. Remove the left parenthesis
Step 7. Exit
Data Structures and Algorithms-Sidra Malik 43
Postfix and Prefix Examples
INFIX RPN (POSTFIX) PREFIX
A+B A B + + A B
A*B+C A B * C + + * A B C
A * (B + C) A B C + * * A + B C
A - (B - (C - D)) A B C D--- -A-B-C D
A-B-C-D A B-C-D- ---A B C D

Prefix : Operators come before


the operands

Data Structures and Algorithms-Sidra Malik 44

You might also like