Unit 4 Stack
Unit 4 Stack
The data structure name indicates itself that organizing the data in memory. It is a way to store and organize
data so that it can be used efficiently. In other words Data Structure can be defined as the group of data
elements which provides an efficient way of storing and organising data in the computer so that it can be used
efficiently. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. Data structures are
the building blocks of any program or the software. Choosing the appropriate data structure for a program is
the most difficult task for a programmer. For example, Array is a collection of memory elements in which
data is stored sequentially, i.e., one after another. In other words, we can say that array stores the elements in
a continuous manner. This organization of data is done with the help of an array of data structures.
The data structure is not any programming language like C, C++, java, etc. It is a set of algorithms that we
can use in any programming language to structure the data in the memory.
As applications are getting complexed and amount of data is increasing day by day, there may arrise the
following problems:
Processor speed: To handle very large amout of data, high speed processing is required, but as the data is
growing day by day to the billions of files per entity, processor may fail to deal with that much amount of
data.
Data Search: Consider an inventory size of 106 items in a store, If our application needs to search for a
particular item, it needs to traverse 106 items every time, results in slowing down the search process.
Multiple requests: If thousands of users are searching the data simultaneously on a web server, then there are
the chances that a very large server can be failed during that process
in order to solve the above problems, data structures are used. Data is organized to form a data structure in
such a way that all items are not required to be searched and required data can be searched instantly.
Unit 4: Data Structure
Efficiency: Efficiency of a program depends upon the choice of data structures. For example: suppose, we
have some data and we need to perform the search for a perticular record. In that case, if we organize our data
in an array, we will have to search sequentially element by element. hence, using array may not be very
efficient here. There are better data structures which can make the search process efficient like ordered array,
binary search tree or hash tables.
Reusability: Data structures are reusable, i.e. once we have implemented a particular data structure, we can
use it at any other place. Implementation of data structures can be compiled into libraries which can be used
by different clients.
Abstraction: Data structure is specified by the ADT which provides a level of abstraction. The client program
uses the data structure through interface only, without getting into the implementation details.
Areas of Application
Data structures are used in any program or software.They are used in the areas of:
Compiler Design.
Operating System.
DBMS.
Graphics.
Simulation.
Numerical Analysis.
Artificial intelligence
The primitive data structures are primitive data types. The int, char, float, double, and pointer are the primitive
data structures that can hold a single value.
The arrangement of data in a sequential manner is known as a linear data structure. The data structures used
for this purpose are Arrays, Linked list, Stacks, and Queues. In these data structures, one element is connected
to only one another element in a linear form. In linear data structures, the elements are stored in non-
hierarchical way where each element has the successors and predecessors except the first and last element.
Arrays: An array is a collection of similar type of data items and each data item is called an element of the
array. The data type of the element may be any valid data type like char, int, float or double.
The elements of array share the same variable name but each one carries a different index number known as
subscript. The array can be one dimensional, two dimensional or multidimensional.
Linked List: Linked list is a linear data structure which is used to maintain a list in the memory. It can be
seen as the collection of nodes stored at non-contiguous memory locations. Each node of the list contains a
pointer to its adjacent node.
Stack: Stack is a linear list in which insertion and deletions are allowed only at one end, called top.
A stack is an abstract data type (ADT), can be implemented in most of the programming languages. It is named
as stack because it behaves like a real-world stack, for example: - piles of plates or deck of cards etc.
Queue: Queue is a linear list in which elements can be inserted only at one end called rear and deleted only
at the other end called front.It is an abstract data structure, similar to stack. Queue is opened at both end
therefore it follows First-In-First-Out (FIFO) methodology for storing the data items.
Unit 4: Data Structure
When one element is connected to the 'n' number of elements known as a non-linear data structure. The best
example is trees and graphs. In this case, the elements are arranged in a random manner.
This data structure does not form a sequence i.e. each item or element is connected with two or more other
items in a non-linear arrangement. The data elements are not arranged in sequential structure.
Trees: Trees are multilevel data structures with a hierarchical relationship among its elements known as
nodes. The bottommost nodes in the hierarchy are called leaf node while the topmost node is called root node.
Each node contains pointers to point adjacent nodes.
Tree data structure is based on the parent-child relationship among the nodes. Each node in the tree can have
more than one child except the leaf nodes whereas each node can have at most one parent except the root
node. Trees can be classified into many categories which will be discussed later in this tutorial.
Graphs: Graphs can be defined as the pictorial representation of the set of elements (represented by vertices)
connected by the links known as edges. A graph is different from tree in the sense that a graph can have cycle
while the tree cannot have the one.
o Static data structure: It is a type of data structure where the size is allocated at the compile time.
Therefore, the maximum size is fixed.
o Dynamic data structure: It is a type of data structure where the size is allocated at the run time.
Therefore, the maximum size is flexible.
1) Traversing: Every data structure contains the set of data elements. Traversing the data structure means
visiting each element of the data structure in order to perform some specific operation like searching or sorting.
Example: If we need to calculate the average of the marks obtained by a student in 6 different subjects, we
need to traverse the complete array of marks and calculate the total sum, then we will divide that sum by the
number of subjects i.e. 6, in order to find the average.
2) Insertion: Insertion can be defined as the process of adding the elements to the data structure at any
location.
If the size of data structure is n then we can only insert n-1 data elements into it.
3) Deletion:The process of removing an element from the data structure is called Deletion. We can delete an
element from the data structure at any random location.
If we try to delete an element from an empty data structure then underflow occurs.
Unit 4: Data Structure
4) Searching: The process of finding the location of an element within the data structure is called Searching.
There are two algorithms to perform searching, Linear Search and Binary Search. We will discuss each one
of them later in this tutorial.
5) Sorting: The process of arranging the data structure in a specific order is known as Sorting. There are many
algorithms that can be used to perform sorting, for example, insertion sort, selection sort, bubble sort, etc.
6) Merging: When two lists List A and List B of size M and N respectively, of similar type of elements,
clubbed or joined to produce the third list, List C of size (M+N), then this process is called merging
Concepts of Stack(LIFO)
Unit 4: Data Structure
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has one end,
whereas the Queue has two ends (front and rear). It contains only one pointer top pointer pointing to the
topmost element of the stack. Whenever an element is added in the stack, it is added on the top of the stack,
and the element can be deleted only from the stack. In other words, a stack can be defined as a container in
which insertion and deletion can be done from the one end known as the top of the stack.
o It is called as stack because it behaves like a real-world stack, piles of books, etc.
o A Stack is an abstract data type with a pre-defined capacity, which means that it can store the elements
of a limited size.
o It is a data structure that follows some order to insert and delete the elements, and that order can be
LIFO or FILO.
o push(): When we insert an element in a stack then the operation is known as a push. If the stack is full
then the overflow condition occurs.
o pop(): When we delete an element from the stack, the operation is known as a pop. If the stack is
empty means that no element exists in the stack, this state is known as an underflow state.
o peep(): It returns the element at the given position.
o display(): It prints all the elements available in the stack.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are four memory blocks in the
stack; therefore, the size of the stack is 4.
Suppose we want to store the elements in a stack and let's assume that stack is empty. We have taken the stack
of size 4 as shown below in which we are pushing the elements one by one until the stack becomes full.
Since our stack is full as the size of the stack is 4. In the above cases, we can observe that it goes from the top
to the bottom when we were entering the new element in the stack. The stack gets filled up from the bottom
to the top.
When we perform the delete operation on the stack, there is only one way for entry and exit as the other end
is closed. It follows the LIFO pattern, which means that the value entered first will be removed last. In the
above case, the value 10 is entered first, so it will be removed only after the deletion of all the other elements.
PUSH operation
POP operation
o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
UPDATE operation
Update operation is required when value of an element at position from the top of the stack needs to be
changed.
o Before updating the element from the stack, we check whether the stack is empty.
o Before updating the element from the stack, we check whether the stack is empty at the given position.
o If the stack is not empty, we change the value of the element at given position from the top.
End if
return
Step 2: [Change the ith element from the top of the stack]
S[top – i + 1] = value
Step 3: Exit
PEEP operation
Peep operation is required to get a value of an element at position from the top of the stack.
o Before displaying the element from the stack, we check whether the stack is empty.
o Before displaying the element from the stack, we check whether the stack is empty at the given
position.
o If the stack is not empty, we get the value of the element at given position from the top.
{
cout<<”underflow”;
return();
}
cout <<”the value at position ” <<i<<”is: ”<<s[top-i+1];
return();
}
void update()
{
int i;
cout <<”enter the position”
cin>>i;
if(top-i+1<=-1)
{
cout<<”underflow”;
return();
}
cout<<”enter the value to be updated”
cin>>val;
s[top-i+1] =val;
return();
}
void display()
{
if(top==-1)
{
cout<<”underflow”;
return();
}
For(i=top;i<=0;i--)
{
cout<<s[i];
}
}
int main()
{
Unit 4: Data Structure
int ch;
do
{
cout<<”\n1.push”;
cout<<”\n2.pop”;
cout<<”\n3.peep”;
cout<<”\n4.update”;
cout<<”\n5.display”;
cout<<”\n0.exit”;
cout<<”\n enter your choice”;
cin>>ch;
switch(ch)
{
case 1: push();
break;
case 2: pop();
break;
case 3: peep();
break;
case 4: update();
break;
case 5: display();
break;
case 0: exit(0);
default: cout<<”enter valid choice”
}
}while(ch!=0);
getch();
}
Program to implement stack using class
#include<iostram.h>
#include<conio.h>
#define max 5
class stack
{
int s[max],top;
Unit 4: Data Structure
public:
stack()
{
top=-1;
}
void push()
{
int val;
if(top>=max-1)
{
cout<<”overflow”;
return();
}
top++;
cout<<”enter the value to be inserted”
cin>>val;
s[top] = val;
return();
}
void pop()
{
if(top==-1)
{
cout<<”underflow”;
return();
}
cout<<”deleted value is: “<<s[top];
top--;
return();
}
void peep()
{
int i;
cout <<”enter the position”
cin>>i;
if(top-i+1<=-1)
Unit 4: Data Structure
{
cout<<”underflow”;
return();
}
cout <<”the value at position ” <<i<<”is: ”<<s[top-i+1];
return();
}
void update()
{
int i;
cout <<”enter the position”
cin>>i;
if(top-i+1<=-1)
{
cout<<”underflow”;
return();
}
cout<<”enter the value to be updated”
cin>>val;
s[top-i+1] =val;
return();
}
void display()
{
if(top==-1)
{
cout<<”underflow”;
return();
}
for(i=top;i<=0;i--)
{
cout<<s[i];
}
}
}
Unit 4: Data Structure
int main()
{
int ch;
stack s1;
do
{
cout<<”\n1.push”;
cout<<”\n2.pop”;
cout<<”\n3.peep”;
cout<<”\n4.update”;
cout<<”\n5.display”;
cout<<”\n0.exit”;
cout<<”\n enter your choice”;
cin>>ch;
switch(ch)
{
case 1: s1.push();
break;
case 2: s1,pop();
break;
case 3: s1.peep();
break;
case 4: s1.update();
break;
case 5: s1.display();
break;
case 0: exit(0);
default: cout<<”enter valid choice”
}
}while(ch!=0);
getch();
}
Applications of stack
Following are the various applications of stack.
1. Recursion
2. Conversion of arithmetic expression
Unit 4: Data Structure
}
int fact(int n)
{
If(n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Conversion of arithmetic expression
Arithmetic expression can be represented in two ways.
1. Parenthesized Expression – Infix Expression
2. Non - parenthesized Expression – prefix/postfix expression
Infix Expression – In this notation operator is placed between its two operators.
Syntax:
OP1 Operator OP2
Example
A + B, A*B
Prefix Expression – in this operator is placed before its two operands. Prefix notations are also called Polish
Notation.
Syntax:
Operator OP1 OP2
Example
+AB, *AB
Postfix Expression – in this operator is placed after its two operands. Prefix notations are also called Reverse
Polish Notation.
Syntax:
OP1 OP2 Operator
Example
AB+, AB*
Unit 4: Data Structure
Ans: ABC*+
Unit 4: Data Structure
Ans: AB*C+
Convert Expression (A+B)*C into postfix expression.
Step 2: (A+B)*C)
Infix string (character scanned) Postfix Stack
(
( ((
A A ((
+ A ((+
B AB ((+
) AB+ (
* AB+ (*
C AB+C (*
) AB+C*
Ans: AB+C*
Practice Questions:
1. A/(B-C+D)
2. (A+B) * (C – D)
3. (A+B) * (C – D) ^ E * F
4. Z + (Y * X - *W / V ^ Y) * T * S
5. (X * Y + Z – W) * S + (T * U / P)
6. A / ( B – C + D) * E + F ^ G
Unit 4: Data Structure
p[j]=pop();
j++;
}
push(infix[i]);
break;
Case ‘+’:
Case ‘-’:
while (s[top]==’^’ || s[top]==’*’ || s[top]==’/’ || s[top]==’+’ || s[top]==’-’)
{
p[j]=pop();
j++;
}
push(infix[i]);
break;
case ‘)’:
while(s[top]!=’(‘)
{
p[j] = pop();
j++;
}
top--;
break;
default:
p[j] =infix[i];
j++;
}
}
p[j] = ‘\0’;
cout<<”postfix expression is: “<<p;
getch();
}
void push(char ch)
{
top++;
s[top]=ch;
}
Unit 4: Data Structure
Char pop()
{
char c;
c = s[top];
top--;
return c;
}
Conversion of infix Expression to Prefix Expression
intopo (infix, prefix)
here,
infix = character array containing infix expression
prefix = character array to store resultant postfix expression
s = stack used to store operators.
Step 1: Push ‘)‘ into stack s.
Step 2: Add ‘(’ at the begining of the infix notation.
Step 3: Scan infix string from right to left and repeat step 4 to 7 un till end of string ‘)’ is encountered.
Step 4: If operand is encountered then add it to prefix string p.
Step 5: if ‘)‘ is encountered then push it into the stack s.
Step 6: if an operator is encountered then do the following steps:
c. Repeatedly pop from the stack s and add it to prefix string p, each operator from the top of the stack
which has higher precedence then the operator.
d. Push the operator into the stack s.
Step 7: If ‘(’ is encountered perform the following steps:
c. Repeatedly pop from the stack s and add it to prefix string p, each operator from the top of the stack
until ‘)‘ is encountered.
d. Remove ‘)‘ from the stack s. (Don’t add it to postfix string p)
[End of loop at step 3]
Step 8: Reverse the prefix expression p.
Step 9: Exit
Examples:
Convert Expression A+B*C into postfix expression.
Step 2: (A+B*C
Infix string (character scanned) Prefix Stack
)
C C )
* C )*
Unit 4: Data Structure
B CB )*
+ CB* )+
A CB*A )+
( CB*A+
Ans: +A*BC
Convert Expression A*B+C into postfix expression.
Step 2: (A*B+C
Infix string (character scanned) Prefix Stack
)
C C )
+ C )+
B CB )+
* CB )+*
A CBA )+*
( CBA*+
Ans: +*ABC
Convert Expression (A+B)*C into postfix expression.
Step 2: ((A+B)*C
Infix string (character scanned) Postfix Stack
)
C C )
* C )*
) C )*)
B CB )*)
+ CB )*)+
A CBA )*)+
( CBA+ )*
( CBA+*
Ans: *+ABC
Practice Questions:
1. A/(B-C+D)
2. (A+B) * (C – D)
3. (A+B) * (C – D) ^ E * F
4. Z + (Y * X - *W / V ^ Y) * T * S
5. (X * Y + Z – W) * S + (T * U / P)
Unit 4: Data Structure
6. A / ( B – C + D) * E + F ^ G
Write a program to convert Infix expression into postfix expression.
#include<iostream.h>
#include<conio.h>
#include<string.h>
char infix[50], p[50], s[50] ;
int top = -1;
void push (char ch);
char pop();
int main()
{
int i, l, j = 0;
cout<<”enter infix expression”
gets(infix);
push(‘)‘);
l = strlen(infix);
for(i=l-1; i>=0;i--)
{
infix[i+1] = infix[i];
}
infix[0] = ‘(’;
infix[l+1] = ‘\0’;
for(i = 0; i <= l; i++)
{
switch(infix[i])
{
case ‘)‘:
push(‘)‘);
break;
case ‘^’:
push(infix[i]);
break;
Case ‘*’:
Case ‘/’:
while (s[top]==’^’)
{
Unit 4: Data Structure
p[j]=pop();
j++;
}
push(infix[i]);
break;
Case ‘+’:
Case ‘-’:
while (s[top]==’^’ || s[top]==’*’ || s[top]==’/’)
{
p[j]=pop();
j++;
}
push(infix[i]);
break;
case ‘(’:
while(s[top]!=’)‘)
{
p[j] = pop();
j++;
}
top--;
break;
default:
p[j] =infix[i];
j++;
}
}
p[j] = ‘\0’;
cout<<”prefix expression is: “<<strrev(p);
getch();
}
void push(char ch)
{
top++;
s[top]=ch;
}
Unit 4: Data Structure
Char pop()
{
char c;
c = s[top];
top--;
return c;
}