You are on page 1of 20

Subject: Data Structures

------------------------------------------------------------------------------------------------------------------------------------------

UNIT–I:

Introduction to Data Structures: Basic Stack Operations, Representation of a Stack


Implementation of stack using Arrays,
Stack Applications: Recursion, In-fix- to postfix Transformation, Evaluating Arithmetic
Expressions

1. What is a data structure? Why we use data structures? What are the types of data
structures? Give examples.(GRIET/June/2015)
Ans: Data Structure:
A data structure is a systematic way of organizing and accessing data.

1. A data structure tries to structure data!


 Usually more than one piece of data
 Should define legal operations on the data
 The data might be grouped together (e.g. in an linked list)

Why Data Structures?

1. Data structures study how data is stored in a computer so that operations can be
implemented efficiently
2. Data structures are especially important when we have large amounts of information
3. Conceptual and concrete ways to organize data for efficient storage and manipulation.

A data structure is an arrangement of data in a computer's memory or even disk storage.

Data structures can be classified into two types

 Linear Data Structures


 Non Linear Data Structures

1
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Linear Data Structures:


Linear data structures are those data structures in which data elements are accessed (read and
written) in sequential fashion ( one by one)
Eg: Stacks , Queues, Linked list

Non Linear Data Structures:


Non Linear Data Structures are those in which data elements are not accessed in sequential
fashion.
Eg: trees, graphs

2. Explain in detail about linear and non linear data structures .


Ans: Stack :

Stack is a Linear data structure which follows Last In First Out (LIFO)mechanism.It means:
the first element inserted is the last one to be removed.Stack uses a variable called top which
points the top most element in the stack. top is incremented while pushing (inserting) an
element into the stack and decremented while popping (deleting) an element from the stack

Valid Operations on Stack:

 Inserting an element into the stack (Push)


 Deleting an element into the stack (Pop)
 Displaying the elements in the stack (Display)
Note:
While pushing an element into the stack, stack is full condition should be checked
While deleting an element from the stack, stack is empty condition should be checked

Applications of Stack:

 Stacks are used in recursion programs


 Stacks are used in function calls
 Stacks are used in interrupt implementation

2
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Queue:
Queue is a linear data structure which follows First in First out (FIFO) mechanism. It means: the
first element inserted is the first one to be removed. Queue uses two variables rear and front.
Rear is incremented while inserting an element into the queue and front is incremented while
deleting element from the queue

Valid Operations on Queue:

 Inserting an element into the queue


 Deleting an element into the queue
 Displaying the elements in the queue

Note:
While inserting an element into the queue, queue is full condition should be checked
While deleting an element from the queue, queue is empty condition should be checked

Applications of Queues:
Real life examples
Waiting in line
Waiting on hold for tech support
Applications related to Computer Science
Threads
Job scheduling (e.g. Round-Robin algorithm for CPU allocation)
Linked List:
Linked list consists of nodes of data which are connected with each other. Every node consists of
two parts data and the link to other nodes. The nodes are created dynamically.

3
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Types of Linked Lists:

 Single linked list


 Double linked list
 Circular linked list
Valid operations on linked list:

 Inserting an element at first position


 Deleting an element at first position
 Inserting an element at end
 Deleting an element at end
 Inserting an element after a given element
 Inserting an element before a given element
 Deleting given element
Trees :
A tree is a Non-Linear data structure which consists of set of nodes called vertices and set of
edges which links vertices
Terminology:

 Root Node: The starting node of a tree is called Root node of that tree
 Terminal Nodes: The node which has no children is said to be terminal node or leaf .
 Non-Terminal Node: The nodes which have children is said to be Non-Terminal Nodes
 Degree: The degree of a node is number of sub trees of that node
 Depth: The length of the largest path from root to terminals is said to be depth or height
of the tree
 Siblings: The children of same parent are said to be siblings
 Ancestors: The ancestors of a node are all the nodes along the path from the root to the
node

4
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

A Property Value
Number of nodes : 9

B C Height : 4

Root Node : A

Leaves : ED, H, I, F, C
D E F
Interior nodes : D, E, G

Number of levels : 5

Ancestors of H : I
G
Descendants of B : D,E, F

H I Siblings of E : D, F

3. What is a stack? Explain in detail the operations on stack .


(or)
What is a stack? Write the algorithms for push and pop operations on stack .

Ans: Stack: Stack is a linear data structure in which a data item is inserted and deleted at one end
(called top of the stack). A stack is based on the principle Last in First Out (LIFO).It means: the
first element inserted into the stack is the last one to be removed from the stack.
Eg: pile of books, stack of plates, stack of coins etc
Operations on stack: Stack supports the following operations:

 PUSH(Inserting an element in to the stack)


 POP(Deleting an element from the stack)
Push operation: push operation is used to insert an element into the stack. The new element is
added at the top most position of the stack. However before inserting the value we have to check
whether there is some space in the stack or not. If an attempt is made to insert a value in a stack
that is already full an error occurs. Therefore before inserting an element into the stack we have
to check the overflow condition. (Stack overflow: Attempt to insert an element when the stack is
full ie top= STACK_SIZE-1).

Algorithm for push operation:


Step 1: if top== STACK_SIZE-1 then print”Stack is full”
Step 2: toptop+1

5
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Step 3 :stack[top]element
Pop operation: The pop operation is used to delete an element from the stack. In pop operation
the topmost element from the stack will be deleted. However before deleting an element from the
stack we have to see whether some element exists in the stack or not i.e if the stack is empty
we cannot do so. Therefore before deleting an element from the stack we have to check the
underflow condition.(Stack underflow : Attempt to delete an element when the stack is empty).

Algorithmfor pop operation :


Step 1 : if top==-1 then print “stack is empty”

Step 2: print stack[top]

4. Explain how to represent a stack in memeory.


Ans:Representation of stack:
If the items A, B, C, D are orderly placed onto the stack collection with four push
operations. The first pop operation would remove D off the stack collection. The second
pop will remove the item C off the stack. The next pop will remove the B off the stack. At
this point, the stack will contain the item A. If a push of item P is then performed on the
stack, the stack will contain A and P. If another pop is performed, the item P will be
removed. The next pop will remove the A from the stack.Since a stack can contain only a
finite number of elements, an error called a stack overflow occurs when the stack is full
and a push operation is performed. Similarly an error called a stack underflow occurs
when the stack is empty and a pop operation is performed.

6
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

5. Write a C program to implement stack using arrays.


Ans Program:
include<stdio.h>
#define STACK_SIZE 100
int stack[STACK_SIZE];

int top=-1;
void push(int);
void pop();
void print();
void main()
{
int item, ch;

while(1)
{
printf ("\NMAIN MENU");
printf ("\n1.PUSH (Insert) in the Stack");
printf ("\n2.POP (Delete) from the Stack");
printf(“\n3.Display”);

printf ("\n4.Exit (End the Execution)");


printf ("\nEnter Your Choice: ");
scanf ("%d", &ch);

7
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

switch (ch)
{
case 1:printf ("\nEnter the Element to be pushed”);
scanf ("%d", &item);

push ( item);
break;
case 2: pop ();
break;
case 3: display();
break;

case 4: exit(0);
}
}
}
/*PUSH FUNCTION*/
void push (int element)

{ if (top == STACK_SIZE-1))
printf(“Stack is full”);
else
{ top=top+1;
stack [top] = element;
}

}
/*POP FUNCTION*/
void pop ()
{
if (top == -1
8
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

printf(“stack is empty”);
else
{ printf(“%d is popped from stack”,stack[top]);
top--;

}
}
/*FUNCTION TO DISPLAY STACK*/
void display (int stack[])
{ int i;
if (top == -1)

printf ("empty");
else
{ printf(“the elements in the stack are”);
for (i=top; i>=0; --i)
printf ("\n--------\n|%3d |\n--------",stack[i]);
}

6. Explain in detail how stacks can be used in a recursive function call with an example.

Ans: Stacks in a recursive function call:


When aprogram runs it gets stored in memory storage unit. Running program gets divided
into three parts.

Stack Segment contains:

I.Stack:Top contains run-time Stack i.e stack of activation records of active functions which
stores function’s local environment i.e return address, arguments, local variables, return
value.

II.Heap: is used to store data allocated run-time.

2.Datapart:contains static data,they are global.

9
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

3.Codepart:contains the program in machine language.

Recursion:
A function calling itself is called a recursive function. (Direct recursion). A function call to another
function, which in turn calls the first function is called indirect recursion.

Recursive functions has two properties


1. There must be certain criteria called base criteria for which the function does not call itself.
2. Each time the function calls itself (directly or indirectly), it must be closer to base criteria.
Every recursive function must have atleast one base case .Otherwise the recursive function will
generate infinite sequence. Recursive functions are executed using stacks. In stack all local
variables ,formal parameters of called function and return values will be stored.Whenever any
function is called all the elements stored in the stack will be restored after a return is executed.
Each recursive call to a function requires that the following information to be pushed onto the
stack.:Local variables, formal parameters and return address :this information is referred as a stack
frame.The stack frame for each function call will be different .The compiler will take care of the
entire stack maintenance when we call recursive function.
Algorithm for factorial using recursion:
1. If n==1 then return 1
2. Factn*factorial(n-1)
3. Return fact
/*function for factorial using recursion*/
longint factorial(int n)

10
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

{
int fact;
if(n==1)
return 1;

else
fact=n*factorial(n-1);
return fact;
}

The following steps are used to represent recursive calls in stack


1. Each time a recursive call is made in the algorithm ,push the necessary information onto the
stack.
2. When the process of pushing all the function calls onto the stack ,pop the top of the stack frame
and pop the top of the function call from the stack indicated by the return address in stack frame
and replace return values of corresponding function call.
3. Continue the process for remaining function calls in the stack until no function calls in the stack.

11
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

7. Write an algorithm to convert a given infix expression to postfix with an example.


(GRIET/June/2015)
(or)
Write a C program to convert a given infix expression to postfix
Ans: Infix to postfix transformation:.
An arithmetic expression can be represented in three ways:
1. Infix: An operator is placed between the operands is called as infix expression
<operand><operator><operand>
Ex: A+B
2. Prefix: An operator is placed befor the operands is called as prefix notation or polish
notation.
<operator><operand><operand>
12
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Ex: + AB
3. Postfix: An operator is placed after the operands is called as potsfix expression or
reverse polish notation or suffix notation.
<opearand><operand><operator>
Ex: AB+
Stacks can be used to evaluate expressions and also to convert expressions from one form to
another form.
Rules for converting expressions:
1. Precedence rules decide the order in which different operators are applied .
High priority: *, /,%
Low priority: + ,-
2. Associativity rule decides the order in which multiple occurrences of the same level of
operators are applied .

Algorithm for infix to postfix transformation:


1. Scan the infix notation from left to right and repeat step2 to step 6 for each character in
infix notation until stack is empty.
2. If left parenthesis ‘(‘ is encountered then push it onto the stack
3. If operand is encountered then add to postfix expression
4. If an operator is encountered then
(a) Repeatedly pop from the stack and add to postfix expression which has the same
precedence than scanned operator
(b) Push scanned operator onto the stack.
5. If right parenthesis ‘)’ is encountered then
(a) Repeatedly pop from the stack and add it to postfix expression until ‘(‘ is
encountered
(b) Remove ‘(‘ from stack and don’t add it to the postfix expression
6. Print postfix expression
Ex:(A*B)-(C*D)

Infix character scanned Stack Postfix expression


( (
( (,(
A (,( A
* (,(,* A
B (,(,* AB
13
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

) ( AB*
- (,- AB*
( (,-,( AB*
C (,-,( AB*C
* (,-,(,* AB*C
D (,-,(,* AB*CD
) (,- AB*CD*
) AB*CD*-

/*program to convert infix to postfix*/


#include<stdio.h>
#define STACK_SIZE 100
char stack[STACK_SIZE];
int top=-1;
void push(char[],char);
char pop(char[]);
intgetpriority(char);
void main()
{
char infix[100],postfix[100],temp;
inti,j=0;
printf("Enter any infix exp:");
scanf(“%s”,infix);
for(i=0;infix[i]!='\0';i++)
{
if(infix[i]=='(')
push(stack,infix[i]);
else if(isalpha(infix[i])||isdigit(infix[i]))
{
postfix[j]=infix[i];
j++;
}
else if(infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/'||infix[i]=='%')
{
while((getpriority(stack[top])>=getpriority(infix[i])))
{ postfix[j]=pop(stack);
j++;
}
push(stack,infix[i]);
}
else if(infix[i]==')')
{
while((stack[top]!='('))

14
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

{
postfix[j]=pop(stack);
j++;
}
temp=pop(stack);
}
}//for
while((top!=-1))
{ postfix[j]=pop(stack);
j++;
}

postfix[j]='\0';
printf("postfix exp is:%s",postfix);

void push(char stack[],char element)


{
if(top==STACK_SIZE-1)
printf("stackoverflow:");
else
{ top++;
stack[top]=element; }
}

char pop(char stack[])


{
charval;
if(top==-1)
printf("under flow:");
else
{ val =stack[top];
top--;}
returnval;
}

intgetpriority(char op)
{
if(op=='/'||op=='*'||op=='%')
return 1;
else if(op=='+'||op=='-')
return 0;
else
return -1;

15
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

8. Write an algorithm to evaluate a postfix expression with an example


(OR)
Write a program to evaluate a postfix expression
Ans: :To evaluate a postfix expression:
The computer usually evaluates an arithmetic expression written in infix notation in two
steps.Firstit converts the expression to postfix notation and then it evaluates the postfix
expression.In each step stack is the main tool that is used to accomplish the given task.

Conversion of Infix to postfix and prefix:

Infix Prefix Postfix


A+B +AB AB+
C*D *CD CD*
(A+B)*C [+AB]*C [AB+]*C
*+ABC AB+C*
A+(B*C) A+[*BC] A+[BC*]
+A*BC ABC*+
(A+B)/(C-D) [+AB]/[-CD] [AB+]/[CD-]
/+AB-CD AB+CD-/

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 onto the stack
 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 onto the stack

Algorithm for evaluation of postfix expression:

1. Scan every character of postfix expression from left to right and repeat step 3 to step
4until end of postfix expression
2. If an operand is encountered, then push it on to the stack.
3. If an operator is encountered, then
a) Pop the top two operands from the stack, where A is the top operand and B is
next-to-top operand.
b) Evaluate B operator A
c) Push the result of evaluation onto the stack
4. Print “result of expression” as the top of the stack.

Evaluate the following expression by using postfix evaluation algorithm


934*8+4/-

16
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Sol: 934*8+4/-

Character scanned Stack


9 9
3 9,3
4 9,3,4
* 9,12
8 9,12,8
+ 9,20
4 9,20,4
/ 9,5
- 4

/*program to implement postfix evaluation*/


#include <stdio.h>
#define STACK_SIZE 100
float stack[STACK_SIZE];
int top=-1;
void push(float[],float);
float pop(float[]);
void main()
{
int i;
float op1,op2,value,result;
charexp[100];
printf("\nenter any postfix expression:");
scanf(“%s”,exp);
for(i=0;exp[i]!='\0';i++)
{
if(isdigit(exp[i]))
push(stack,(float)(exp[i]-'0'));
else
{
op2=pop(stack);
op1=pop(stack);
switch(exp[i])
{
case '+':value=op1+op2;
break;
case '-':value=op1-op2;
break;
case '/':value=op1/op2;
break;
case '*':value=op1*op2;
break;

17
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

case '%':value=(int)op1%(int)op2;
break;
}
push(stack,value);
}
}
result=pop(stack);
printf("\nvalue of the postfix expression=%.2f",result);
}

void push(float stack[],float val)


{
if(top==STACK_SIZE-1)
printf("\n stack overflow");
else
{
top++;
stack[top]=val;
}
}
float pop(float stack[])
{
floatval;
if(top==-1)
printf("\n stack underflow");
else
{
val=stack[top];
top--;
}
returnval;
}

9. Define Recursion? With examples explain about Tail and Non-Tail Recursion.
(GRIET/June/2015)
Ans:

Recursion:A function which calls itself is called a recursive function, the call is recursive call
and the process of function implementation is recursion.

Tail Recursion: Tail Recursion is another form of recursion,

A recursive function is said to be tail recursion if no operations are pending to be performed


when the recursive function returns to its caller. where the function makes a recursive call as its
very last operation.

18
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

Tail recursive functions are highly desirable because they are much more efficient to use the
amount of information that has to be stored on the system stack is independent of the number
of recursive calls.
Example:

int fact(int n)

{
return fact1(n,1);
}
int fact1(int n, int res)
{
if(n==1)
return res;
else
return fact1(n-1,n*res);
}
Non tail Recursion: whenever there is a pending operation to be performed, the function
becomes non-tail recursive. In such a non-tail recursive function, information about each
pending operation must be stored, so the amount of information directly depends on the
number of calls.
Example:

factorial(n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
When returning back from a recursive call, there is still one pending
operation, multiplication.Therefore, factorial is a non-tail recursive method
10. Give the applications of Stack.
Ans:
1. Converting a decimal number into a binary number
2. The simplest application of a stack is to reverse a word.
3. "undo" mechanism in text editors; this operation is accomplished by keeping all text
changes in a stack.
4. Language processing:
 space for parameters and local variables is created internally using a stack.
 compiler's syntax check for matching braces is implemented by using stack.
 support for recursion
5. Expression Conversion
 Infix to Postfix
 Infix to Prefix
19
Subject: Data Structures
------------------------------------------------------------------------------------------------------------------------------------------

 Postfix to Infix
 Prefix to Infix
6. Expression Evaluation

11. Convert the following Infix expression into Prefix expression? x+b-y+d*e/a.
(GRIET/June/2015)
Ans:
x+b-y+d*e/a ->x+b-y+[*de]/a
x+b-y+[/*dea]
[+xb]-y+[/*dea]
[-+xby]+[/*dea]
+-+xby/*dea

20

You might also like