Module2 Stack
Module2 Stack
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.
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.
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 .
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.
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.
#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;
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:
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.
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.
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
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
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.
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.