0% found this document useful (0 votes)
1 views8 pages

Module2 Stack

This document provides an in-depth overview of stacks as a linear data structure that operates on the Last In First Out (LIFO) principle, detailing its basic operations such as push, pop, and peek. It also discusses the implementation of stacks using arrays, the concept of multiple stacks, and the evaluation of arithmetic expressions in infix, postfix, and prefix notations. Additionally, it highlights various applications of stacks including reversing lists, checking parentheses, and supporting recursion.
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)
1 views8 pages

Module2 Stack

This document provides an in-depth overview of stacks as a linear data structure that operates on the Last In First Out (LIFO) principle, detailing its basic operations such as push, pop, and peek. It also discusses the implementation of stacks using arrays, the concept of multiple stacks, and the evaluation of arithmetic expressions in infix, postfix, and prefix notations. Additionally, it highlights various applications of stacks including reversing lists, checking parentheses, and supporting recursion.
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/ 8

Data Structure (PCC2011)

Module 2 STACK
Detailed Content: Introduction to Stack, Stack as ADT, ADT Operations on Stack, Array
Implementation of Stack, Multiple Stacks, Evaluation of Arithmetic Expression

Introduction to Stack:
A stack is a non-primitive linear data structure in which items are
added or removed only at one end, called top of the stack. A stack is
based on LIFO principle that means the data item that is inserted last
into the stack is the first one to be removed from the stack. In a stack,
only two operations are typically performed: pushing, which adds an
item to the top, and popping, which removes the top item. This
structure allows access only to the top element, limiting how items are
inserted and removed.
Example: Plates in cafeteria.
• Plates can be added by placing on top.
• Plates may be taken only from the top.

Basic features of Stack:


 Stack is an ordered list of similar data type.
 Stack is a LIFO(Last in First out) structure.
 push() function is used to insert new elements into the Stack and pop() function is used to remove
an element from the stack. Both insertion and removal are allowed at only one end of Stack called
Top.
 Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state
if it is completely empty.

Stack as ADT
The stack abstract data type (ADT) is characterized by a specific structure and set of operations. It is an
ordered collection of elements where additions and removals occur only at one end, referred to as the
"top". Stacks operate under the LIFO (last-in, first-out) principle. The primary operations for a stack are
outlined below:
• Stack(): This method creates a new, empty stack. It does not take any parameters and simply
returns an empty stack.
• push(item): This method adds a new item to the top of the stack. It requires the item to be
added, but does not return a value.
• pop(): This operation removes and returns the top item from the stack. It takes no parameters
but modifies the stack.
• peek(): This method returns the top item of the stack without removing it. It requires no
parameters.
• isEmpty(): This method checks if the stack is empty, returning a Boolean value. No parameters
are required.
• size(): This method returns the number of items currently in the stack, providing the size as an
integer without requiring parameters.

ADT Operations on Stack


A stack supports three basic operations: push, pop, and peek. The push operation adds an element to
the top of the stack and the pop operation removes the element from the top of the stack. The peek
operation returns the value of the topmost element of the stack.

Module 2: - STACK Page 1 of 8


Data Structure (PCC2011)
Push Operation:
The push operation is used to insert an element into the stack. The new element is added at the topmost
position of the stack. However, before inserting the value, we must first check if TOP=MAX–1, because if
that is the case, then the stack is full and no more insertions can be done. If an attempt is made to insert a
value in a stack that is already full, an OVERFLOW message is printed.

To insert an element with value 6, we first check if TOP=MAX–1 . If the condition is false, then we
increment the value of TOP and store the new element at the position given by stack[TOP] . Thus,
following diagram shows the updated stack .

The algorithm to insert an element in a stack is:


In Step 1, we first check for the OVERFLOW condition.
In Step 2,TOP is incremented so that it points to the next location in the array.
In Step 3, the value is stored in the stack at the location pointed by TOP.

Step 1: If TOP = MAX-1 Print “Overflow” Goto step 4[End of If]


Step 2: Set TOP = TOP + 1
Step 3: Set Stack[TOP] = value
Step 4: End

Pop Operation:
The pop operation is used to delete the topmost element from the stack. However, before deleting the
value, we must first check if TOP=NULL because if that is the case, then it means the stack is empty and
no more deletions can be done. If an attempt is made to delete a value from a stack that is already empty,
an UNDERFLOW message is printed. Consider the stack given in Fig.

To delete the topmost element, we first check if TOP=NULL. If the condition is false, then we decrement
the value pointed by TOP. Thus, the updated stack becomes as shown in Fig.

Step 1 : If TOP = NULL print “UNDERFLOW” Goto step 4


Step 2 : Set val = Stack[TOP]
Step 3 : Set TOP = TOP-1
Step 4 : End

Peek Operation
Peek is an operation that returns the value of the topmost element of the stack without deleting it from
the stack. The algorithm for Peek operation is given in Fig. 7.11. However, the Peek operation first checks
if the stack is empty, i.e., if TOP = NULL, then an appropriate message is printed, else the value is
returned. Consider the stack given in the following figure.

Module 2: - STACK Page 2 of 8


Data Structure (PCC2011)
Here, the Peek operation will return 5, as it is the value of the topmost element of the stack.

Step 1: IF TOP = NULL PRINT STACK IS EMPTY Goto Step 3


Step 2: RETURN STACK[TOP]
Step 3: END

Array Implementation of Stack:


In the computer’s memory, stacks can be represented as a linear array. Every stack has a variable called
TOP associated with it, which is used to store the
address of the topmost element of the stack. It is
this position where the element will be added to or
deleted from. There is another variable called MAX,
which is used to store the maximum number of
elements that the stack can hold.

If TOP = NULL, then it indicates that the stack is


empty and if TOP = MAX–1, then the stack is
full.(MAX–1 is written because array indices start
from 0).
C Program to perform Push, Pop, and Peek operations on a stack by using an array.

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int top= -1,c,stack[MAX];
void push();
void pop();
void peek();
void display();
int main()
{
printf("\n1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit\n");
while(1)
{
printf("Enter your choice(1-5):");
scanf("%d",&c);
switch(c)
{
case 1:push(); break;
case 2: pop(); break;
case 3: peek(); break;
case 4: display(); break;
case 5: exit(0); break;
default: printf("Enter correct choice.");
}
}
}
void push()
{
int val;

Module 2: - STACK Page 3 of 8


Data Structure (PCC2011)
if(top==MAX-1)
printf("Stack is full.\n");
else
{
printf("Enter the element to insert into stack: ");
scanf("%d",&val);
top=top+1;
stack[top]=val;
}
}
void pop()
{
int val;
if(top== -1)
printf("Stack is empty.\n");
else
{
val=stack[top];
printf("\nthe deleted element is %d .\n",val);
top=top-1;
}
}
void peek()
{
if(top==-1)
printf("Stack is empty.\n");
else
{
printf("\nThe topmost element in the stack is %d.\n ",stack[top]);
}
}
void display()
{
int i;
if(top==-1)
printf("Stack is empty.\n");
else
{
printf("Elements is stack are..\n");
for(i=0;i<=top;i++)
printf("%d\n",stack[i]);
}
}

Multiple Stacks:
While implementing a stack using an array we face two issues:
First the size of the array must be known in advance. If the stack is allocated less space, then frequent OVERFLOW
conditions will be encountered.
Second, in case we allocate a large amount of space for the stack, it may result in sheer wastage of memory. Thus,
there lies a trade-off between the frequency of overflows and the space allocated. So, a better solution to deal with
this problem is to have multiple stacks or to have more than one stack in the same array of sufficient size.
Multiple stacks can be implemented in two ways:

Module 2: - STACK Page 4 of 8


Data Structure (PCC2011)
First Approach:
• The first subarray would be stack 1, and the second subarray would be stack 2.
• The stack1 would be from 0 to n/2, and stack2 would be from n/2 to n-1.
• Overflow condition occurs even there is a space left in the array.

Second Approach:
• In this case, both the stacks start from the extreme corners, i.e., Stack1 starts from the leftmost corner (at
index 0), and Stack2 starts from the rightmost corner (at index n-1). Stack1 extends in the right direction,
and stack2 extends in the left direction.
• This approach provides a space-efficient implementation means that when the array is full, then only it will
show the overflow error.

Evaluation of Arithmetic Expression


The stack organization is very effective in evaluating arithmetic expressions. An expression is defined
as a number of operands or data items combined using several operators.
A + B

Operand 2
Operand 1

Operator
Expressions are usually represented in three different ways:
 Infix
 Postfix
 Prefix

Infix notation:
While writing an arithmetic expression using infix notation, the operator is placed in between the
operands. For example, A+B; here, plus operator is placed between the two operands A and B. Although it
is easy for us to write expressions using infix notation, computers find it difficult to parse as the
computer needs a lot of information to evaluate the expression. Information is needed about operator
precedence and associativity rules, and brackets which override these rules.

Postfix notation:
A postfix notation, also called as Reverse Polish Notation or RPN. In postfix notation, as the name
suggests, the operator is placed after the operands. For example, if an expression is written as A+B in
infix notation, the same expression can be written as AB+ in postfix notation. The order of evaluation of a
postfix expression is always from left to right. Even brackets cannot alter the order of evaluation. The
expression (A + B) * C can be written as: [AB+]*C AB+C* in the postfix notation A postfix operation does
not even follow the rules of operator precedence. The operator which occurs first in the expression is
operated first on the operands. For example, given a postfix notation AB+C*. While evaluation, addition
will be performed prior to multiplication.

Module 2: - STACK Page 5 of 8


Data Structure (PCC2011)
Polish notation (Prefix notation):
It refers to the notation in which the operator is placed before its two operands. For example, if A+B is an
expression in infix notation, then the corresponding expression in prefix notation is given by +AB. While
evaluating a prefix expression, the operators are applied to the operands that are present immediately on
the right of the operator. Like postfix, prefix expressions also do not follow the rules of operator
precedence and associativity, and even brackets cannot alter the order of evaluation

Evaluation of postfix expression consider an expression 562+*84/-

Input Operand 1 Operand 2 operator Value stack


symbol

5 5

6 56

2 562

+ 6 2 + 6+2=8 58

* 5 8 * 5*8-40 40

8 40 8

4 40 8 4

/ 8 4 / 8/4=2 40 2

- 40 2 - 40-2=38 38

End of Print the


_ _ _ Stack empty
Input result 38

Show the effect of PUSH and POP operation on the stack of size 10. The stack contains 10, 20, 22,
26. 28, and 30 with 30 being at the top of the stack. Show diagrammatically the effect of following
given operation: (i) PUSH 46. (ii) PUSH 48, (ii) POP (iv) POP. (v) POP.

9 9 9 9 9 9
8 8 8 8 8 8
7 7 top 7 48 7 7 7
6 top 6 46 6 46 top 6 46 6 6
top 5 30 5 30 5 30 5 30 top 5 30 5
4 28 4 28 4 28 4 28 4 28 top 4 28
3 26 3 26 3 26 3 26 3 26 3 26
2 22 2 22 2 22 2 22 2 22 2 22
1 20 1 20 1 20 1 20 1 20 1 20
0 10 0 10 0 10 0 10 0 10 0 10
PUSH PUSH POP POP POP
46 48

Module 2: - STACK Page 6 of 8


Data Structure (PCC2011)
Applications of Stack:
The applications of stack are listed below:
1. Reversing a list
2. Parentheses checker
3. Evaluation of a postfix expression
4. Recursion
5. Tower of Hanoi
6. Function Calls
7. Undo/Redo Operations in Text Editors
8. Back Button in Web Browsers
Reversing a List: A list of numbers can be reversed by reading each number from an array starting from
the first index and pushing it on a stack. Once all the numbers have been read, the numbers can be
popped one at a time and then stored in the array starting from the first index

Implementing Parentheses Checker: Stacks can be used to check the validity of parentheses in any
algebraic expression. For example, an algebraic expression is valid if for every open bracket there is a
corresponding closing bracket. For example, the expression (A+B} is invalid but an expression {A + (B –
C)} is valid.

Evaluation of a postfix expression: Using stacks, any postfix expression can be evaluated very easily.
Every character of the postfix expression is scanned from left to right. If the character encountered is an
operand, it is pushed on to the stack. However, if an operator is encountered, then the top two values are
popped from the stack and the operator is applied on these values. The result is then pushed on to the
stack.

Recursion: It is defining large and complex problems in terms of smaller and more easily solvable
problems. In recursive functions, a complex problem is defined in terms of simpler problems and the
simplest problem is given explicitly.

A recursive function is defined as a function that calls itself to solve a smaller version of its task until a
final call is made which does not require a call to itself. Since a recursive function repeatedly calls itself, it
makes use of the system stack to temporarily store the return address and local variables of the calling
function.

Tower of Hanoi: The tower of Hanoi is one of the main applications of recursion. It says, ‘if you can solve
n–1 cases, then you can easily solve the nth case’.

Undo/Redo Operations in Text Editors: One of the most common uses of Stack in programming is to
implement undo and redo functionality in text editors and other applications. When the user types text,
each keystroke is pushed onto a stack. When the user hits undo, the most recently pushed text is popped
off the Stack and removed from display. Redo pops the item back onto the Stack. As Stack maintains LIFO
order, the text removed last is undone first. Visual editors like Photoshop also use it for undo/redo image
edits.

Module 2: - STACK Page 7 of 8


Data Structure (PCC2011)
Back Button in Web Browsers: The back button in browsers allows users to go to the previous web
page. When a user clicks a link to a new page, the current URL is pushed onto the browser stack. When
the back is clicked, the most recent URL is popped to return to the previous page. Without a stack, the
browser would have to keep track of the entire history, which is inefficient. The Stack only stores the
essential last in, first out order to enable this back navigation efficiently.

Function Calls: Stack plays an important role in programs that call several functions in
succession. Suppose, a program containing three functions: A, B, and C. function A invokes function B,
which invokes the function C. unction A will only be completed after function B is completed and function
B will only be completed after function C is completed. Therefore, function A is first to be started and last
to be completed.

Advantages of Stacks:
 Simplicity: Stacks are a simple and easy-to-understand data structure, making them suitable for a
wide range of applications.
 Efficiency: Push and pop operations on a stack can be performed in constant time , providing
efficient access to data.
 Last-in, First-out (LIFO): Stacks follow the LIFO principle, ensuring that the last element added
to the stack is the first one removed. This behavior is useful in many scenarios, such as function
calls and expression evaluation.
 Limited memory usage: Stacks only need to store the elements that have been pushed onto
them, making them memory-efficient compared to other data structures.

Disadvantages of Stacks:
 Limited access: Elements in a stack can only be accessed from the top, making it difficult to
retrieve or modify elements in the middle of the stack.
 Potential for overflow: If more elements are pushed onto a stack than it can hold, an overflow
error will occur, resulting in a loss of data.
 Not suitable for random access: Stacks do not allow for random access to elements, making
them unsuitable for applications where elements need to be accessed in a specific order.
 Limited capacity: Stacks have a fixed capacity, which can be a limitation if the number of
elements that need to be stored is unknown or highly variable.

Module 2: - STACK Page 8 of 8

You might also like