0% found this document useful (0 votes)
11 views13 pages

Stack

This document provides an overview of stacks, a linear data structure that follows the Last In First Out (LIFO) principle. It details the Stack Abstract Data Type (ADT), including operations such as push, pop, and peek, and discusses two implementations: array and linked list. Additionally, it covers applications of stacks in matching delimiters and evaluating expressions in infix, prefix, and postfix notations.

Uploaded by

shresthabiju6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views13 pages

Stack

This document provides an overview of stacks, a linear data structure that follows the Last In First Out (LIFO) principle. It details the Stack Abstract Data Type (ADT), including operations such as push, pop, and peek, and discusses two implementations: array and linked list. Additionally, it covers applications of stacks in matching delimiters and evaluating expressions in infix, prefix, and postfix notations.

Uploaded by

shresthabiju6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 2: Stacks

Stacks
§ A stack is a linear data structure that follows LIFO (Last in First Out) order to perform operations.
§ Storing and retrieving operations can be performed only at one of its ends called top or tos (top of
stack).
§ Such a stack resembles piles of trays in a cafeteria. New trays are put on the top of the pile and top
tray is the first tray removed from the stack. For this reason, a stack is called a LIFO structure: last in
/first out.

The Stack ADT


A stack of element of type T is a finite sequence of elements of T together with the operation:
1. createEmptyStack() : Create an empty stack
2. isEmpty() : Check to see if the stack is empty or not.
3. isFull() : Check to see if the stack is full or not.
4. Push (el) : Put the element el on the top of stack.
5. Pop() : Take the topmost element from the stack.
6. peek() : return the top element of the stack

Stack can be implemented in two ways:

1. Array Implementation of stack


2. Linked List Implementation of stack

1
Array implementation of stack
Structure for stack
struct stack
{
int stck[maxsize]; // declaring an array
int top; // top of a stack
}
struct stack s;

Creating an empty stack:


• The empty stack contains no elements and can therefore be indicated by top equaling -1.
• To initialize a stack s to the empty state, we may initially execute s.top = -1

Condition for an empty stack:


if(s.top == -1)
// stack is empty;
else
// stack is not empty;

Function:
int isEmpty(struct stack *ps)
{
if(ps->top == -1)
return 1;
else
return 0;
}

Creating a full stack:


• This is the situation when the stack becomes full. The stack top is present at the highest location
(i.e., maxsize-1).
Condition for a full stack:
if (s.top == maxsize-1)
// stack is full;
else
// stack is not full;

Function:
int isFull (struct stack *ps)
{
if(ps->top == maxsize -1)
return 1;
else
return 0;
}

2
A. Push Operation:
• The process of insertion of new items onto a stack is called push operation.
• For performing push operation, check to see whether the stack is full or not.
• If we try to push an element onto a full stack, the condition is called stack overflow.
• The stack is full when top = size-1

Algorithm that pushes an ITEM into a stack:


Step 1: If TOP = Size-1, then
a) print “Stack Overflow”
b) exit
Step 2: Set TOP = TOP+1
Step 3: Set STCK [TOP] = ITEM
Step 4: Exit

Method to push an item onto a stack:


void push (struct stack *ps, int item)
{
if(ps->top == size - 1)
printf (“Stack Overflow”);

else
{
printf (“Enter the element to be inserted:”);
scanf(“%d”, &item);
ps->stck[++(ps->top)] = item;
}
}

B. Pop Operation:
• The process of deletion of the topmost item from a stack is called pop operation.
• For performing pop operation, check to see whether the stack is empty or not.
• If we try to pop an element from an empty stack, the condition is called stack underflow.
• The stack is empty when top < 0 or top = -1

Algorithm that pop an ITEM from a stack: Method to pop an item from a stack:

Step 1: If TOP < 0, then int pop (struct stack *ps)


a) print “Stack Underflow” {
b) exit if (top == - 1)
Step 2: else remove the topmost element printf (“Stack Underflow”);
else
Step 3: Set ITEM = STCK[TOP]
return (ps->stck[ps->top--]);
Step 4: Set TOP = TOP-1 }
Step 5: Return

3
Linked List implementation of stack
A linked list of nodes could be used to implement a stack. Linked list representation of stack is nothing but
a liked list of nodes where each node is element of the stack. To point to the top most node we have a
pointer top that points to node recently added. Every new node is added to the beginning of the liked list
and top point to it. The main advantage of this representation is that size of stack is not fixed so there is
least chance of stack overflow.
Structure for stack

struct linked_stack
{
int info;
struct linked_stack *next;
} *top;

Push operation:

Step 1: Create a newNode with given value


Step 2: Check to see if stack is empty (i.e., top == NULL)
a) If it is empty, then set newNode->next = NULL
b) else set newNode->next = top
Step 3: Set top = newNode

Function:

Void push(int item)


{
struct node *newNode;
newNode = (struct node *) malloc (sizeof(struct node));
newNode->info = item;
if(top == NULL)
{
newNode->next = NULL;
top = newNode;
}
else
{
newNode->next = top;
top = newNode;
}
}

4
POP Operation:
Step 1: Check to see if stack is empty (i.e., top == NULL)
a) If it is empty
print “Stack is empty”
return
b) else
define a node pointer temp
set temp = top
Step 2: Set top = top->next
Step 3: Delete temp i.e., free(temp)

Function:

void pop()
{
struct node *temp;
if (top == NULL)
{
printf(“Stack is empty”);
return;
}
else
{
temp = top;
top = top->next;
free(temp);
}
}

5
Application of Stack:

1. Matching delimiters in a program:


• Delimiters in C program are: parenthesis “(” and “)” , curly braces “{” and “}”, brackets “[” and ”]”
and comment “/*” and “*/”

Algorithm for Matching delimiters in a program:

1. Start
2. read a character ch from file;
3. while not end of file
a) if ch is ‘(’, ‘[’, or ‘{’
push(ch);
b) else if ch is '/'
read the next character;
if this character is '*'
skip all characters until “*/” is found
and report an error if the end of file is reached before “*/” is encountered;
else ch = the character read in;
continue; // go to the beginning of the loop;
c) else if ch is ‘)’, ‘]’, or ‘}’
if ch and popped off delimiter do not match
failure;
d) read next character ch from file;
4. if stack is empty
print success;
else
print failure;
5. Stop

6
2. Evaluating Infix, Prefix and Postfix Expressions:
Infix expression:
• Infix expression is a mathematical notation in which operator is written in between the operands.
• Example: A+B, where A and B are operands and + is an operator.

Prefix expression:
• Prefix expression is a mathematical notation in which the operator preceds the two operands.
• Example: +AB, where A and B are operands and + is an operator.

Postfix expression:
• Infix expression is a mathematical notation in which the operator is written after the operands.
• Example: AB+, where A and B are operands and + is an operator.

Note: Prefix and Postfix are parenthesis free expressions.

• Postfix notation is most suitable for a computer to calculate any expression.


• Postfix notation is the universally accepted notation for designing Arithmetic and Logical Unit (ALU)
of the CPU (processor). Therefore, it is necessary to study the postfix notation.
• Any expression entered into the computer is first converted into postfix notation, stored in stack
and then calculated.

Advantages of using Postfix Notation:


• Using infix notation, one cannot tell the order in which operators should be applied.
• Whenever an infix expression consists of more than one operator, the precedence rules (BODMAS)
should be applied to decide which operator (and operand associated with that operator) is
evaluated first.
• But in postfix expression operands appear before the operator, so there is no need for operator
precedence and other rules.

Notation Conversions
• Let A + B * C be the given expression, which is an infix notation. To calculate this expression for
values 4, 3, 7 for A, B, C respectively we must follow certain rule (called BODMAS in general
mathematics) in order to have the right result.
• For example: A + B * C = 4 + 3 * 7 = 7 * 7 = 49
• The answer is not correct; multiplication is to be done before the addition, because multiplication
has higher precedence over addition. This means that an expression is calculated according to the
operator’s precedence not the order as they look like.
• The error in the above calculation occurred, since there were no braces to define the precedence of
the operators. Thus, expression A + B * C can be interpreted as A + (B * C).
• Using this alternative method, we can convey to the computer that multiplication has higher
precedence over addition.

7
CONVERTING INFIX TO POSTFIX EXPRESSION:

The rules to be remembered during infix to postfix conversion are:


1. Parenthesize the expression starting from left to light.
2. During parenthesizing the expression, the operands associated with operator having higher
precedence are first parenthesized.
3. The sub-expression (part of expression), which has been converted into postfix, is to be treated as
single operand.
4. Once the expression is converted to postfix form, remove the parenthesis.

Converting infix expression, A + B * C to postfix form is:

A+B*C Infix Form


= A + (B * C) Parenthesized expression
= A + (B C *) Convert the multiplication
= A (B C *) + Convert the addition
= ABC*+ Postfix Form

Algorithm to convert Infix to Postfix Notation:


1. Start
2. Scan one character at a time of an infix expression from left to right.
3. opstack = the empty stack
4. Repeat till there is data in infix expression
4.1 if scanned character is ‘(’
push it to opstack
4.2 if scanned character is operand
push it to postfix string
4.3 if scanned character is operator
while (opstack != -1 && precedence(opstack[otop]) > precedence (scan character))
pop and push it into postfix string
otherwise
push scanned character into opstack
4.4 if scanned character is ‘)’
pop and push into postfix string until ‘(’ is not found and ignore both symbols
5. pop and push it into postfix string until opstack is not empty
6. Stop

Example 1: A+B*C

Scan character Postfix String opstack


A A
+ A +
B AB +
* AB +*
C ABC +*
ABC* +
ABC*+

8
Example 2: (A+B)*C

Scan character Postfix String opstack


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

Example 3: ((A-(B+C))*D)$(E+F)

Scan character Postfix String opstack


( (
( ((
A A ((
- A (( -
( A (( - (
B AB (( - (
+ AB (( - ( +
C ABC (( - ( +
) ABC + (( -
) ABC + - (
* ABC + - (*
D ABC + - D (*
) ABC + - D *
$ ABC + - D * $
( ABC + - D * $(
E ABC + - D * E $(
+ ABC + - D * E $(+
F ABC + - D * EF $(+
) ABC + - D * EF + $
ABC + - D * EF + $
Convert following Infix expressions into Postfix expressions
1. P+Q–(R*S/T+U)-V*W
2. A+(B/C-(D*E^F) +G) *H
3. A+ [(B + C) +(D+E) *F]/G
4. (A+B) *C/D+E^A/B
5. ((A+B)-C*D/E) *(H-I) *F+G
6. ((H*((((A+((B+C) *D)) *F) *G) *E)) +J)

9
Converting Infix expressions to Prefix expressions:

• The precedence rule for converting an infix expression into prefix expression is identical to that of
infix to postfix.
• Only change is that the operator is placed before the operands.

Convert the given infix expressions into prefix expressions:

(i) A+B-C
= +AB-C
= -+ABC

(ii) A$B*C-D+E/F/(G+H)
= A$B*C-D+E/F/(+GH)
= $AB*C-D+E/F/(+GH)
= *$ABC-D+E/F/(+GH)
= *$ABC-D+ (/EF)/(+GH)
= *$ABC-D+ (//EF+GH)
= -*$ABCD+ (//EF+GH)
= +-*$ABCD//EF+GH

Convert following Infix expressions into Prefix expressions


1. P+Q–(R*S/T+U)-V*W
2. A+(B/C-(D*E^F)+G)*H
3. A+ [(B + C) +(D+E) *F]/G
4. (A+B) *C/D+E^A/B
5. ((A+B)-C*D/E) *(H-I) *F+G

10
Evaluating the Postfix Expression
Procedures to evaluate postfix expression:
• Each time we read an operand we push it onto a stack.
• When we reach an operator, its operands will be the top two elements on the stack.
• We then pop these two elements from stack and perform the indicated operation on them.
• Then push the result on the stack so that it will be available for use an operand of the next operator.

Algorithm to evaluate postfix expression:


1. Scan one character at a time from left to right of the given postfix expression
1.1 if scanned character is an operand
read its corresponding value and push it into vstack;
1.2 if scanned character is an operator
pop and assigned to op2;
pop and assigned to op1;
compute the result according to given operator and push result into vstack;
2. pop and display which is required value of the given postfix expression;
3. Stop

Examples:
(i) 345*+
= 3 20+ [ multiply 4 and 5]
= 23 [ add 3 and 20]

Tracing:
character op2 op1 result vstack
3 3
4 34
5 345
* 5 4 20 3 20
+ 20 3 23

(ii) 623+-382/+*2^3+
= 6 5 -382/+*2^3+
= 1 382/+*2^3+
= 1 3 4+*2^3+
= 1 7 *2^3+
= 7 2^3+
= 49 3+
= 52

11
623+-382/+*2^3+

character op2 op1 result vstack


6 6
2 62
3 623
+ 3 2 5 65
- 5 6 1 1
3 13
8 138
2 1382
/ 2 8 4 134
+ 4 3 7 17
* 7 1 7 7
2 72
^ 2 7 49 49
3 49 3
+ 3 49 52 52

(iii) 123+*321-+*

(iv) 48-2569/+1-*-3-

Evaluating the Prefix Expression


(i) +5*32
= +5 6 // *32 = 3*2
= 11 // +56 = 11

(ii) /+53-42
= / 8 -42
= /8 2
=4

12
Transform each of the following prefix expressions to infix:

(i) +-ABC
= + A-B C
= A-B+C

(ii) ++A-*^BCD/+EF*GHI

(iv) +-^ABC*D**EFG

Transform each of the following postfix expressions to infix:

(i) AB+C-
= A+BC-
= A+B-C
(ii) ABC+-
= AB+C-
= A-B+C

(iii) AB-C+DEF-+^

=A-B+C ^ D+E-F

(iv) ABCDE-+^*EF*-

13

You might also like