Вы находитесь на странице: 1из 44

RIZAL TECHNOLOGICAL UNIVERSITY

Mandaluyong

Data Structures and


Algorithms

Lesson 3

Stacks

ITC 211: Data Structure and Algorithm Prepared by: Jaevier Angcao Villanueva, MIT
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.
Insertion and deletion on stack
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
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.
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
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
Static Implementation
 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
Static Implementation
23
1
12

Problem with this implementation


 Every PUSH and POP requires moving the entire array up
and down.
Static Implementation

Since, in a stack the insertion and deletion


take place only at the top, so…
A better Implementation:
 Anchor the bottom of the stack at the
bottom of the array
 Let the stack grow towards the top of the
array
 Top indicates the current position of the first
stack element.
Static Implementation
A better Implementation:

top 1 First Element


Second Element
2
.
.
maxlength Last Element
Stack Example
Stack Implementation (array)
#include <iostream>
#define STACK_SIZE 5
using namespace std;
int stackNum[STACK_SIZE];
int top=-1;
void pop();
void push(int);
void display();
Stack Implementation (continued)
int main()
{
while(1){
int choice,num;
system("cls");
cout<< "[1] - Push \n";
cout<< "[2] - Pop \n";
cout<< "[3] - Display \n";
cout<< "[4] - Exit \n";
cout<< "\n====================\n";
cout<< "Enter your choice: ";
cin>> choice;
Stack Implementation (continued)
switch(choice){
case 1:
cout<<"Enter number to push: ";
cin>>num;
push(num); break;
case 2:
pop(); break;
case 3:
display(); break;
Stack Implementation (continued)
case 4:
exit(1);
default :
cout<<"\nInvalid Choice";
}
cout<<endl<<endl;
system("pause>0");
return 0;
}
Stack Implementation (continued)
void pop()
{
if(top==-1)
cout<<"\nStack is Empty\n";
else
cout<<"You remove " <<
stackNum[top--];
}
Stack Implementation (continued)
void push(int n)
{
if(top==STACK_SIZE-1)
cout<<"Stack is full";
else
stackNum[++top]=n;
}
Stack Implementation (continued)
void display()
{
if(top==-1)
cout<<"\nstack is empty\n";
else
for(int i=top;i>=0;i--)
cout<<stackNum[i]<<endl;
}
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
• Converting decimal to binary
• Reversing the order of elements in an array
• Evaluating arithmetic expression
• Saving local variables when one function calls
another, and this one calls another, and so on.
C++ Run-time Stack
• The C++ run-time system keeps track
of the chain of active functions with a
stack

• When a function is called, the run-


time system pushes on the stack a
frame containing
– Local variables and return value
– Program counter, keeping track of the
statement being executed

• When a function returns, its frame is


popped from the stack and control is
passed to the method on top of the
stack
Infix, Prefix, and Postfix
• Infix notation
– Operator is written in-between the
operands.
• Prefix notation
– Polish notation
– Operators is written before the operands
• Postfix notation
– Suffix notation or reverse polish notation
– Operators is written after the operands
Operator Precedence
^ - Exponential operator
*, / - Multiplication, Division
+, - - Addition, Subtraction
Sample Problem
• Given the expression A + B * C
• Solve the infix, prefix and postfix
Solution
• Infix
A+B *C
Solution
• Prefix
A + (B * C) parenthesized the expression
A + (* B C) convert the sub expression to
prefix (multiplication)
+ A (* B C) convert to prefix (addition)
+ A * BC remove the parenthesis
• postfix
A + (B * C) parenthesized the expression
A + (B C *) convert the sub expression to
postfix (multiplication)
A (B C *) + convert to postfix (addition)
AB C *+ remove the parenthesis
INFIX-PREFIX-POSTFIX NOTATIONS
Infix, Postfix and Prefix notations are
three different but equivalent ways of
writing expressions. It is easiest to
demonstrate the differences by looking
at examples of operators that take two
operands.
Infix notation: X + Y
Operators are written in-between their
operands.

This is the usual way we write expressions.


An expression such as A * ( B + C ) / D is
usually taken to mean something like: "First
add B and C together, then multiply the
result by A, then divide by D to give the final
answer."
Postfix notation (also known as "Reverse Polish
notation"): X Y +

Operators are written after their operands. The


infix expression given above is equivalent to
ABC+*D/

The order of evaluation of operators is always left-


to-right, and brackets cannot be used to change
this order. Because the "+" is to the left of the "*"
in the example above, the addition must be
performed before the multiplication.
Operators act on values immediately to the left of
them. For example, the "+" above uses the "B"
and "C". We can add (totally unnecessary)
brackets to make this explicit:

( (A (B C +) *) D /)

Thus, the "*" uses the two values immediately


preceding: "A", and the result of the addition.
Similarly, the "/" uses the result of the
multiplication and the "D".
Prefix notation (also known as "Polish
notation"): + X Y

Operators are written before their operands. The


expressions given above are equivalent to

/*A+BCD

As for Postfix, operators are evaluated left-to-right and


brackets are superfluous. Operators act on the two
nearest values on the right. I have again added (totally
unnecessary) brackets to make this clear:
(/ (* A (+ B C) ) D)
Example:

Infix Postfix Prefix

A*B+C/D

A * (B + C) / D

A * (B + C / D)
Infix Postfix Prefix

A*B+C/D AB*CD/+ +*AB/CD

A * (B + C) / D ABC+*D/ /*A+BCD

A * (B + C / D) ABCD/+* *A+B/CD
Converting between these notations
The most straightforward method is to start by
inserting all the implicit brackets that show the
order of evaluation e.g.:

Infix Postfix Prefix

( (A * B) + (C / D) ) ( (A B *) (C D /) +) (+ (* A B) (/ C D) )

((A * (B + C) ) / D) ( (A (B C +) *) D /) (/ (* A (+ B C) ) D)

(A * (B + (C / D) ) ) (A (B (C D /) +) *) (* A (+ B (/ C D) ) )
You can use a similar trick to convert to and from parse
trees - each bracketed triplet of an operator and its two
operands (or sub-expressions) corresponds to a node of
the tree. The corresponding parse trees are:
Infix - Postfix
Algorithm : Infix to Postfix Conversion
In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation
is abc*+. The algorithm for the conversion is as follows :
• Scan the Infix string from left to right.
• Initialise an empty stack.
• If the scannned character is an operand, add it to the Postfix string. If the scanned
character is an operator and if the stack is empty Push the character to stack.
• If the scanned character is an Operand and the stack is not empty, compare the
precedence of the character with the element on top of the stack (topStack). If
topStack has higher precedence over the scanned character Pop the stack else
Push the scanned character to stack. Repeat this step as long as stack is not
empty and topStack has precedence over the character.

Repeat this step till all the characters are scanned.


• (After all characters are scanned, we have to add any character that the stack may
have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop
the stack. Repeat this step as long as stack is not empty.

• Return the Postfix string.

Example :

Let us see how the above algorithm will be


imlemented using an example.

Infix String : a+b*c-d


Initially the Stack is empty and our Postfix string
has no characters. Now, the first character
scanned is 'a'. 'a' is added to the Postfix string.
The next character scanned is '+'. It being an
operator, it is pushed to the stack.

Postfix string

Stack
Next character scanned is 'b' which will be placed
in the Postfix string. Next character is '*' which is
an operator. Now, the top element of the stack is
'+' which has lower precedence than '*', so '*'
will be pushed to the stack.

Postfix string

Stack
The next character is 'c' which is placed in the Postfix string. Next
character scanned is '-'. The topmost character in the stack is '*'
which has a higher precedence than '-'. Thus '*' will be popped out
from the stack and added to the Postfix string. Even now the stack
is not empty. Now the topmost element of the stack is '+' which
has equal priority to '-'. So pop the '+' from the stack and add it to
the Postfix string. The '-' will be pushed to the stack.

Postfix string

Stack
Next character is 'd' which is added to Postfix string. Now
all characters have been scanned so we must pop the
remaining elements from the stack and add it to the
Postfix string. At this stage we have only a '-' in the stack.
It is popped out and added to the Postfix string. So, after
all characters are scanned, this is how the stack and
Postfix string will be :

Postfix string

Stack
Infix - Prefix
STEP 1 : Read the given infix expression into string called infix.

STEP 2 : Reverse the infix string and read one character at a time
and perform the following operations :

If the read character is an operand,


then add the operand to the prefix string.
If the read character is not an operand, then check
If the stack is not empty and precedence of the top of the
stack operator is higher than the read operator,
then pop the operator from stack and add this
operator to the prefix string.
Else push the operator onto the stack.
STEP 3 : Repeat STEP 2 till all characters are processed
from the input string.

STEP 4 : If stack is not empty, then pop the operator


from stack and add this operator to the
prefix string.

STEP 5 : Repeat STEP 4 till all the operators are popped


from the stack.

STEP 6 : Reverse the prefix string and display the result


of the given infix expression or the resultant
prefix expression stored in a string called
prefix from this algorithm.

Вам также может понравиться