SlideShare una empresa de Scribd logo
1 de 64
Syllabus for B.Tech. I Year II semester
Code:121CS01 DATA STRUCTURES AND C++
UNIT – I
Introduction to data structures: Abstract data type(ADT), Stacks and Queues circular queues and
their implementation with arrays. Stack applications: infix to post fix conversion, postfix
expression evaluation. Applications of queues.
UNIT – II
Singly linked lists, doubly linked lists, circular list and their operations, representing stacks and
queues with linked lists.
UNIT – III
Trees- Binary tress, terminology, representation, traversals
Graphs- terminology, representation, graph traversals (dfs & bfs).
UNIT - IV
Searching - Linear and binary search methods.
Sorting - Bubble sort, selection sort, Insertion sort, Quick sort, merge sort.
UNIT – V
Introduction to c++ programming-object oriented programming concepts, Structured Vs OOP.
Classes and objects-class definition, Objects, class scope and accessing members, Constructors-
default constructor, parameterized constructor, constructor initialization list, copy constructor.
Destructors.
UNIT – VI
Static class members, this pointer, friend functions, Dynamic memory management with operators
new and delete.Overloading-function overloading, Operator overloading, restrictions on
operator overloading, overloading unary and binary operators,templates, inheritance.
• Code: 121CS71 DATASTRUCTURES AND C++ LAB
(Common to all Branches)
1.Write a C program that implement stack and its operations using arrays
2. Write a C program that implement Queue and its operations using arrays.
3. Write a C program that uses Stack operations to perform the following
i) Converting infix expression into postfix expression
ii) Evaluating the postfix expression
4. Write a C program that uses functions to perform the following operations on singly
linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal
5. Write a C program that uses functions to perform the following operations on doubly
linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways
6 Write a C program that uses functions to perform the following:
i) Creating a Binary Tree of integers
ii) Traversing the above binary tree in preorder, in order and post order.
7. Write C programs that use both recursive and non recursive functions to perform the
following searching operations for a Key value in a given list of integers :
i) Linear search ii) Binary search
8. Write C programs that implement the following sorting methods to sort a given list of integers in
ascending order:
i) Bubble sort ii) Quick sort
9. Write C programs that implement the following sorting methods to sort a given list of integers in
ascending order:
i)Insertion sort ii) Merge sort iii) Selection Sort
10. Write a C++ program that prints all real solutions to the quadratic equation ax2+bx+c=0.
Read in a,b,c and use the quadratic formula. If the descremainant b2-4ac is negative,
display a message stating that there are no real solutions.
11. A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0 and
Subsequent terms are found by adding the preceding two terms in the sequence. Write a C++
program to generate the first n terms of the sequence.
12. Write a C++ program that checks whether a given string is palindrome or not.
UNIT-I
 Topics to be covered
 1.Introduction to data structures.
 2. Abstract data type (ADT)
 3. Stacks and queues
 4. Circular queues and their implementation with arrays.
 5. Stack applications:
5.1. infix to post fix conversion
5.2. postfix expression evaluation.
 6. Applications of queues
Introduction to data structures
Data- it is a collection of items or values
Type- it is a collection of values.
ex- integer- 0 to 9
boolean- true or false
Data type- it is a data of type and together with the
set of operations used to apply on the type.
ex- integer is a member of type integer and its
operations are addition, subtraction etc…
1.Introduction to data
structures.
 Definition:- A data structure is an arrangement of data in a
computers memory or even on disk storage. It has a different
way of storing and organizing (accessing) data in a computer.
 Objective of data structure:- manipulation of real-life data
requires the following essential tasks-
1.storage representation of user data
2. Retrieval of stored data
3. transformation of user data
• Mathematical definition of data
structure is D=(d,f,a)
where
D= data structure
d= a set of variables (data objects).
f= a set of functions
a= set of rules to implement the
functions.
2. Abstract data type
(ADT)
 Data structure is implemented around the concept of
an abstract data type that defines the data together
with the operations.
 ADT contains
- data
- operations
- no implementation details.
 ADT is also called as user defined data type.
 Only tells about what are the data values required and
what operations performed on those objects.
Overview of data structures
Several data structures are available in the
computer science and used based on their
applications.
Data structures are classified into different types.
Data structure
Linear ds
Non Linear
ds
Array
s
Linked list stack queue
s
Tree
s
Graph
s
1.Linear data structure-
all the elements are stored in sequential
order or linear order means that all the
elements are adjacent to each other. Each
element has exactly two neighbors.
Predecessor and successor.
• the first element does not have predecessor
• The last element does not have successor.
2. Non linear data structure- no such sequence
in elements, if one element is connected to a
more than two adjacent element then it is a
non linear data structure.
Applications of data
structures
Implementing data bases of different
organizations (ds used is B-Trees)
Implement compilers for different
languages (ds used is hash tables).
Used in every program and software
system.
3. Stacks and queues
Definition - A stack is an ordered collection of
homogeneous data elements, where the insertion and
deletion takes place at one end, known as TOP.
 The stack is also called LAST IN FIRST OUT(LIFO)
 It means: the element which is inserted last must be
deleted first
 Example
1. No of plates in cafeteria
2. stack of coins
 Stack maintains a pointer called top, which keeps trackStack maintains a pointer called top, which keeps track
of the top most element in the stack.of the top most element in the stack.
 Any insertions or deletions should be based upon theAny insertions or deletions should be based upon the
value of top.value of top.
 It works on the basis of LIFO (Last in First out).It works on the basis of LIFO (Last in First out).
 According to the definition, new elements are insertedAccording to the definition, new elements are inserted
from top and the elements are deleted from same endfrom top and the elements are deleted from same end
i.e again top.i.e again top.
 This suggests that the element inserted most recentlyThis suggests that the element inserted most recently
can only be deleted.can only be deleted.
 In the stack, the elements are removed in the reverseIn the stack, the elements are removed in the reverse
order of that in which they were added to the stack i.eorder of that in which they were added to the stack i.e
last element inserted is to be deleted first.last element inserted is to be deleted first.
 So it is called last in first out.So it is called last in first out.
 Stack has structured with two operationsStack has structured with two operations
1.1. push- insertion adding elements on to a stackpush- insertion adding elements on to a stack
2.2. Pop- deletion  removing element from the stackPop- deletion  removing element from the stack
Basic operations:Basic operations:
The basic operations are insertion, deletionThe basic operations are insertion, deletion
,display.,display.
In stacks, special terms are given for insertIn stacks, special terms are given for insert
and delete. i.e push for insert and pop is forand delete. i.e push for insert and pop is for
delete.delete.
Push: inserting or adding element into thePush: inserting or adding element into the
stack is called push.stack is called push.
Pop: deleting or removing element from thePop: deleting or removing element from the
stack is called pop.stack is called pop.
Elements are inserted in the order as A,B,C,D,EElements are inserted in the order as A,B,C,D,E
It represents the stack of 5 elements.It represents the stack of 5 elements.
The top most element in the stack is EThe top most element in the stack is E
If we want to delete element E has to be deleted firstIf we want to delete element E has to be deleted first
Pop operation- delete element from the
stack
Example :-
ADT For Stack
ADT for stack
struct stack
{
int stack[5],top;
}
void push();
void pop();
void display();
Implementing stack usingImplementing stack using
arraysarrays
Algorithm for inserting element into the stack:Algorithm for inserting element into the stack:
Algorithm push()Algorithm push()
1. if top=(SIZE-1)1. if top=(SIZE-1)
then write (‘stack overflow’)then write (‘stack overflow’)
elseelse
2. read item or data2. read item or data
3. top3. top top+1←top+1←
4. stack[top] item←4. stack[top] item←
5. stop5. stop
Explanation:Explanation:
 The stack is of size max. This procedure inserts an elementThe stack is of size max. This procedure inserts an element
item on to the top of a stack which is represented by anitem on to the top of a stack which is represented by an
array stack.array stack.
 The first step of this algorithm checks for an overflowThe first step of this algorithm checks for an overflow
condition.condition.
 Overflow means inserting element into a stack which isOverflow means inserting element into a stack which is
full.full.
 If the top value reaches to maximum size of the stack thenIf the top value reaches to maximum size of the stack then
elements cannot be inserted into the stack i.e. stack is full.elements cannot be inserted into the stack i.e. stack is full.
 Otherwise top is incremented by one and element isOtherwise top is incremented by one and element is
inserted into the stack.inserted into the stack.
Algorithm to delete elements from the stack:Algorithm to delete elements from the stack:
Algorithm pop()Algorithm pop()
1. if top=-11. if top=-1
then write (‘stack underflow’)then write (‘stack underflow’)
elseelse
2. item2. item ← stack[top]← stack[top]
3. top ← top-13. top ← top-1
Explanation:Explanation:
This procedure deletes an element from the stack.This procedure deletes an element from the stack.
The first step of this algorithm checks forThe first step of this algorithm checks for
underflow condition.underflow condition.
If the top value is -1 then stack is empty.If the top value is -1 then stack is empty.
Empty stack is known as underflow.Empty stack is known as underflow.
Takeout the element from the location where, theTakeout the element from the location where, the
top is pointing and then decrement top by one.top is pointing and then decrement top by one.
Display of stack:Display of stack:
Printing the contents of stack after push and popPrinting the contents of stack after push and pop
operations.operations.
Algorithm print()Algorithm print()
1. if top=-11. if top=-1
then write (‘stack empty’)then write (‘stack empty’)
2. Repeat for i2. Repeat for i ← top to 0← top to 0
print(stack[i])print(stack[i])
3. stop3. stop
 A queue is a linear data structure in which insertion take place from oneA queue is a linear data structure in which insertion take place from one
end calledend called rear endrear end and deletions take place from other end calledand deletions take place from other end called frontfront
endend i.e insertion and deletion take place from different ends.i.e insertion and deletion take place from different ends.
 The principle used to in queue isThe principle used to in queue is FIFO.(First In First Out)FIFO.(First In First Out)
 FIFOFIFO- the element which is inserted First must be deleted First.- the element which is inserted First must be deleted First.
 In a queue there are two variables one is theIn a queue there are two variables one is the rearrear and other one isand other one is frontfront..
 the element must be alwaysthe element must be always added at rearadded at rear end andend and removed from theremoved from the
frontfront..
Basic operations on queue:Basic operations on queue:
The operations that can be performed on queue areThe operations that can be performed on queue are
 Insertion EnqueueInsertion Enqueue
 Deletion DequeueDeletion Dequeue
 DisplayDisplay
QueuesQueues
Front rear
Bus Stop
Queue
Bus
Stop
front
rear
rear rear rear rear
Bus Stop Queue
Bus
Stop
front
rear
rear rear
Bus Stop
Queue
Bus
Stop
front
rear
rear
Bus Stop Queue
Bus
Stop
front
rear
rear
FrontRear
Front
Rear
Front
Rear
•A queue is like a line of people waiting forA queue is like a line of people waiting for
• a bank teller. The queue has aa bank teller. The queue has a frontfront and aand a rearrear..
New people must enter the queue at the rear.New people must enter the queue at the rear.
When an item is taken from the queue, it always comes from the front.When an item is taken from the queue, it always comes from the front.
• Different types of queues
1. Linear queue or queue
2. Circular queue
3. Doubly ended queue( dequeue)
4. Priority queue
This type of data structure is used in timeThis type of data structure is used in time
sharing systems where many user jobs will besharing systems where many user jobs will be
waiting in the system queue for processing.waiting in the system queue for processing.
These jobs may request the services of CPU,These jobs may request the services of CPU,
main memory or external devices such asmain memory or external devices such as
printer.printer.
Working of a linear queue:-
i) Initially front=rear= -1. It indicates queue is empty.
0 1 2 3 4
front=rear=-1
0 1 2 3 4
ii) Add 10
10
front rear
0 2 3 4
iii) Add 20
front rear
1
10 20
0 2 3 4
iv) Add 30
front rear
1
10 20 30
0 2 3 4
v) Add 40
front rear
1
10 20 30 40
0 2 3 4
vi) Add 50
front rear
1
10 20 30 40 50
0 2 3 4
vii) Add 60 (overflow)
front rear
1
10 20 30 40 50
0 2 3 4
viii) delete (10 is removed)
front rear
1
20 30 40 50
0
front rear
1
30 40 50
ix) delete (20 is
removed)
2 3 4
0
front rear
1
40 50
x) delete (30 is removed)
2 3 4 0
front rear
1
50
xi) delete (40 is
removed)
2 3 4
0
front=rear=-1
1
ix) delete (underflow)
2 3 40
front=rear=-1
1
xii) delete (50 is removed)
2 3 4
Implementation of queue usingImplementation of queue using
arrayarray
Algorithm insert( )Algorithm insert( )
1.1. If rearIf rear ≥≥ size-1size-1
then write (‘overflow’)then write (‘overflow’)
2.2. Read itemRead item
3.3. rearrear←← rear + 1rear + 1
4.4. queue[rear]queue[rear]←← itemitem
5.5. If(front==-1)If(front==-1)
6.6. front++;front++;
7.7. stopstop
Explanation:Explanation:
This procedure adds an element item to theThis procedure adds an element item to the
queue.queue.
First it checks for an overflow condition.First it checks for an overflow condition.
If the rear value reaches or exceeds size of thIf the rear value reaches or exceeds size of th
queuequeue
then elements cannot be inserted into the queuethen elements cannot be inserted into the queue
ie. Overflow.ie. Overflow.
Whenever element is inserted into the queue,Whenever element is inserted into the queue,
rear is increment by onerear is increment by one
and place the element in the locationand place the element in the location
where rear is pointing.where rear is pointing.
Algorithm to delete element from the queueAlgorithm to delete element from the queue
Algorithm delete()Algorithm delete()
1.1. If (front= = -1)or (front> rear)If (front= = -1)or (front> rear)
then write (‘queue underflow’)then write (‘queue underflow’)
itemitem ←← queue [front]queue [front]
2. front2. front ←← front + 1front + 1
Explanation:Explanation:
This procedure deletes an element from the queue.This procedure deletes an element from the queue.
The first step of this algorithm checks for underflow condition.The first step of this algorithm checks for underflow condition.
If the front value is -1or greater than rear then queue is empty.If the front value is -1or greater than rear then queue is empty.
Take out the element from the location where, the front is pointing andTake out the element from the location where, the front is pointing and
store it in the variable, then increment front by one.store it in the variable, then increment front by one.
Algorithm to display elements in a queueAlgorithm to display elements in a queue
1.1. if((front==-1)||(front>rear))if((front==-1)||(front>rear))
1.1 print statck is Underflow1.1 print statck is Underflow
2. Else2. Else
2.1 repeat for i->front to rear2.1 repeat for i->front to rear
2.2. print queue[i];2.2. print queue[i];
Drawback in queue
In a queue when the rear pointer reaches to the end of the queue,
insertion would be denied even if room is available at the front
one way to remove this is using the circular queue
Program: implementation of queue using array
# include <stdio.h>
# define size 4
void insertion();
void deletion();
void display();
int front=-1,rear=-1,item,choice,queue[size];
void main()
{clrscr();
while(1)
{
printf("n*** MENU ***n 1. INSERTIONn 2. DELETIONn
3.TRAVERSEn 4. EXITn");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:insertion();
break;
case 2:deletion();
break;
case 3:display();
break;
case 4:exit();
void insertion()
{
if(rear>=size-1)
printf("*** queue is full ***n");
else
{
printf("enter item into queue:");
scanf("%d",&item);
rear++;
queue[rear]=item;
if(front==-1)
front++;
} }
void deletion()
{
if((front==-1)||(front>rear))
printf("*** queue is empty ***n");
else
{
item=queue[front];
front++;
printf("the deleted item from queue is
%dn",item);
}
}
void display(){
int i;
if((front==-1)||(front>rear))
printf("*** queue is empty ***n");
else
{
printf("n elements in queue:- ");
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
}}
EMPTY QUEUE
Circular queues
Q[0] Q[1] Q[2] Q[3] Q[N]
Delete element 5
rear
• How to test whether circular queue is empty or full?
• The circular q is controlled by the MOD operation.
• Circular queue is empty
when front =-1
rear=-1
Circular queue is full
front = (rear+1)% SIZE
Implementation of circular queue using
array
• Algorithm for insertion
1.if((front == 0 && rear == SIZE-1) || (front == (rear+1)%size)
2.printf("Queue Overflow n");
return;
3.if (front == -1) /*If queue is empty */
3.1 front = 0;
3.2 rear = 0;
4.else
5.if(rear == SIZE-1)/*rear is at last position of queue */
6.rear = 0;
7. else
8.rear = rear+1;
9.Read item
10.cq[rear] = item ;
11.end
• Algorithm for deletion
• 1.if (front == -1)
2.printf("Queue Underflown")
return
3.if(front == rear) /* queue has only one element */
3.1front = -1;
3.2rear=-1;
4.else
5.if(front == SIZE-1)
• front = 0;
6.else
7.front = front+1;
8.Stop
int insert(){
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
cq[rear] = item ;
printf("the element %d at %d position and front=
%d,rear=%dn",cq[rear],rear,front,rear);
return;
}/*End of insert()*/
int del()
{
if (front == -1)
{
printf("Queue Underflown");
return ;
}
printf("Element deleted from queue is :
%dn",cq[front]);
if(front == rear) /* queue has only one
element */
{
front = -1;
rear=-1;
}
else
if(front == SIZE-1)
front = 0;
else
front = front+1;
printf("front=%d,rear=
%dn",front,rear);
return;
}/*End of del() */
Deletion
display() int display(){
int front_pos = front,rear_pos = rear;
if(front == -1){
printf("Queue is emptyn");
Return;}
printf("Queue elements :n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos){
printf("%d ",cq[front_pos]);
front_pos++;}
else{
while(front_pos <= SIZE-1){
printf("%d ",cq[front_pos]);
front_pos++;}
front_pos = 0;
while(front_pos <= rear_pos){
printf("%d ",cq[front_pos]);
front_pos++;}}/*End of else */
printf("n");
return;
}/*End of display() */
Applications of queues
There are several applications of queues in computer science.
1. Implement various aspects of operating systems.
2. CPU scheduling in Multiprogramming environment- single CPU has to
serve more than one program simultaneously.
3. Round Robin CPU scheduling algorithm.
4. In operating System maintains a queue of processes that are ready
to process or that are waiting for particular event to occur.
5. Computer system maintains a buffer and is implemented as a queue.
6. Printer
7. Call waiting when you are attending other call
8. a file server in a computer network handles file access request from
many clients throughout the network. Servers have a limited capacity
to service request from clients. when that capacity is exceeded,
client requests wait in queues
9. This type of data structure is used in time sharing systems where many9. This type of data structure is used in time sharing systems where many
user jobs will be waiting in the system queue for processing. Theseuser jobs will be waiting in the system queue for processing. These
jobs may request the services of CPU, main memory or externaljobs may request the services of CPU, main memory or external
devices such as printer.devices such as printer.
Circular queue using array
# include<stdio.h>
#include<stdlib.h>
# define SIZE 4
int insert();
int del();
int display();
int cq[SIZE];
int front = -1;
int rear = -1;
main(){
while(1){
printf("1.Insertn");
printf("2.Deleten");
printf("3.Displayn");
printf("4.Quitn");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
insert();
break;
case 2 :
del();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choicen");
}/*End of switch*/
}/*End of while */
}/*End of main()*/
int insert(){
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
cq[rear] = item ;
printf("the element %d at %d position and front=
%d,rear=%dn",cq[rear],rear,front,rear);
return;
}/*End of insert()*/
example
1.encq(A)
2.encq(B)
3.encq(c )
4. Encq ( D )
5.Decq
6.encq(E)
7. Decq
8.encq( F)
9.Decq
10. Decq
11.Decq
12. Decq
Applications of stacksApplications of stacks
Parenthesis matching.Parenthesis matching.
Evaluation of postfix expressions.Evaluation of postfix expressions.
Infix to prefix conversions.Infix to prefix conversions.
Infix to postfix conversions.Infix to postfix conversions.
Recursion.Recursion.
Quick sort.Quick sort.
1.Parenthesis matching1.Parenthesis matching
The objective of this function is to check theThe objective of this function is to check the
matching of parenthesis in an expressionmatching of parenthesis in an expression
i.ei.e
 In an expression the no of left parenthesis mustIn an expression the no of left parenthesis must
be equal to no: of right parenthesis.be equal to no: of right parenthesis.
Ex:Ex: ((A+B)*C)((A+B)*C)
This is a valid expression because in this no ofThis is a valid expression because in this no of
left parenthesis (2) = no: of right parenthesis (2).left parenthesis (2) = no: of right parenthesis (2).
Conversion of expressionsConversion of expressions
Arithmetic expressions can be represented in three ways:Arithmetic expressions can be represented in three ways:
 Infix notationInfix notation
 Prefix notationPrefix notation
 Postfix notationPostfix notation
1. Infix notation- In which operator should be placed in between the two operands.
Example- A+B C-D E*F G/H.
2. Prefix notation (polish notation)-
• Operator preceded by the operand is called prefix notation
Examples
+AB -CD *EF GH.
3. Postfix notation(reverse polish notation or suffix notation)-
• Operator should be placed after operands.
AB+ CD- EF* GH
Notations – Conversions
Consider the infix expression: 2 + 3 * (5 – 7) / 9
Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))
Transfer the operators to the beginning of parentheses
(+ 2 (/ (* 3 (– 5 7)) 9))
Remove the parentheses: + 2 / * 3 – 5 7 9
This is the equivalent prefix expression.
Transfer the operators to the end of parentheses
(2 ((3 (5 7 –) *) 9 /) +)
Remove the parentheses: 2 3 5 7 – * 9 / +
This is the equivalent postfix expression.
Examples
Infix
Expression
Prefix
Expression
Postfix
Expression
2 + 3 + 2 3 2 3 +
2 + 3 * 5 + 2 * 3 5 2 3 5 * +
(2 + 3) * 5 * + 2 3 5 2 3 + 5 *
2 * 3 – (5 + 9)
– * 2 3 +
5 9
2 3 * 5 9 +
–
Infix to post fix(RPN) Conversion
Algorithm to convert infix expression to RPN:
1. Declare a stack.
2. Repeat the following steps until the end of the infix expression is
reached.
1. Get input token (constant, variable, arithmetic operator, left
parenthesis, right parenthesis) in the infix expression.
2. If the token is
1. A left parenthesis: Push it onto the stack.
2. A right parenthesis:
1. Pop and display stack elements until a left parenthesis is on the
top of the stack.
2. Pop the left parenthesis also, but do not display it.
3. An operator:
1. While the stack is nonempty and token has lower or equal
priority than stack top element, pop and display.
2. Push token onto the stack.
4. An operand: Display it.
3. When the end of the infix expression is reached, pop and display stack
items until the stack is empty.
Note
• 1. the lower precedence operator
never placed on top of the higher
precedence.
Operator Precedence
Infix expression- (A+B)^C-(D*E)/F
Infix Stack Post fix
( ( Empty
A ( A
+ (+ A
B (+ AB
) Empty AB+
^ ^ AB+
C ^ AB+C
- - AB+C^
( -( AB+C^
D -( AB+C^D
* -(* AB+C^D
E -(* AB+C^DE
) - AB+C^DE*
/ -/ AB+C^DE*
F -/ AB+C^DE*F
Empty AB+C^DE*F/-
Postfix (reverse polish notation)
expression evaluation
• Algorithm
1.Scan expression from left to right and repeat steps 2 and 3 for each
element of expression.
2. If an operand is encountered, put it on stack.
3.If an operator op1 is encountered then
3.1 remove the top two elements of stack, where A is the top and B is
the next top element.
3.2 evaluate B op1 A
3.3 push the result back on to the stack.
4. set the top value on stack.
5. stop
Evaluate the expression
• Postfix:- 5,6,2,+,*,12,4,/,-
Symbol scanned stack content
5 5
6 5 6
2 5 6 2
+ 5 8
* 40
12 40 12
4 40 12 4
/ 40 3
Convert infix to postfix expression
1. (A-B)*(D/E)
2. (A+B^D)/(E-F)+G
3. A*(B+D)/E-F*(G+H/K)
4. ((A+B)*D)^(E-F)
5. (A-B)/((D+E)*F)
6. ((A+B)/D)^((E-F)*G)
7. 12/(7-3)+2*(1+5)
8. 5+3^2-8/4*3+6
9. 6+2^3+9/3-4*5
10. 6+2^3^2-4*5
Evaluate the postfix expression
1. 5,3,+,2,*,6,9,7,-,/,-
2. 3,5,+,6,4,-,*,4,1,-,2,^,+
3. 3,1,+,2,^7,4,1,-,2,*,+,5.-
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int priority(char c);
int push(char c);
int pop();
static char str[30];
int top=-1;
void main()
{
char in[30],post[30],ch;
int i,j,l;
printf("enter the string");
gets(in);
l=strlen(in);
Write a C program to convert infix to postfix evaluation
for(i=0,j=0;i<l;i++){
if(isalpha(in[i]))
post[j++]=in[i];
else
{
if(in[i]=='(')
push(in[i]);
else if(in[i]==')')
while((ch=pop())!='(')
post[j++]=ch;
else
{
while(priority(in[i])<=priority(str[top]))
post[j++]=pop();
push(in[i]);
}}}while(top!=-1)
post[j++]=pop();
post[j]='0';
printf("n equivalent infix to postfix is:
%s",post);
}
int priority (char c)
{
switch(c)
{
case'+':
case'-': return 1;
case'*':
case'/':
return 2;
case'$':return 3;
case '^':return 4;
}
return 0;
}
int push(char c)
{str[++top]=c;
}
pop()
{
return(str[top--]);
}

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Data structures using C
Data structures using CData structures using C
Data structures using C
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
Data Structure
Data StructureData Structure
Data Structure
 
Data structures
Data structuresData structures
Data structures
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Data structures
Data structuresData structures
Data structures
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Preparation Data Structures 01 introduction
Preparation Data Structures 01 introductionPreparation Data Structures 01 introduction
Preparation Data Structures 01 introduction
 
Data structures Basics
Data structures BasicsData structures Basics
Data structures Basics
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Preparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listPreparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_list
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)
 

Similar a Unit i(dsc++)

Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddumaneesh boddu
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptxDwijBaxi
 
Data Structure
Data Structure Data Structure
Data Structure Ibrahim MH
 
Stacks
StacksStacks
StacksAcad
 
Ds
DsDs
DsAcad
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptxselemonGamo
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)mailmerk
 
CD3291 2.5 stack.pptx
CD3291 2.5 stack.pptxCD3291 2.5 stack.pptx
CD3291 2.5 stack.pptxmareeswari15
 
Data Structures by Yaman Singhania
Data Structures by Yaman SinghaniaData Structures by Yaman Singhania
Data Structures by Yaman SinghaniaYaman Singhania
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfarpitaeron555
 

Similar a Unit i(dsc++) (20)

Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx
 
Data structures
Data structuresData structures
Data structures
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
 
DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
 
Data Structure
Data Structure Data Structure
Data Structure
 
Stacks
StacksStacks
Stacks
 
Ds
DsDs
Ds
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)
 
CD3291 2.5 stack.pptx
CD3291 2.5 stack.pptxCD3291 2.5 stack.pptx
CD3291 2.5 stack.pptx
 
Data Structures by Yaman Singhania
Data Structures by Yaman SinghaniaData Structures by Yaman Singhania
Data Structures by Yaman Singhania
 
Datastructure
DatastructureDatastructure
Datastructure
 
Lab Manual-OOP.pdf
Lab Manual-OOP.pdfLab Manual-OOP.pdf
Lab Manual-OOP.pdf
 
Data Structures
Data StructuresData Structures
Data Structures
 
Data structure
Data structureData structure
Data structure
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 

Último

Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 

Último (20)

Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 

Unit i(dsc++)

  • 1. Syllabus for B.Tech. I Year II semester Code:121CS01 DATA STRUCTURES AND C++ UNIT – I Introduction to data structures: Abstract data type(ADT), Stacks and Queues circular queues and their implementation with arrays. Stack applications: infix to post fix conversion, postfix expression evaluation. Applications of queues. UNIT – II Singly linked lists, doubly linked lists, circular list and their operations, representing stacks and queues with linked lists. UNIT – III Trees- Binary tress, terminology, representation, traversals Graphs- terminology, representation, graph traversals (dfs & bfs). UNIT - IV Searching - Linear and binary search methods. Sorting - Bubble sort, selection sort, Insertion sort, Quick sort, merge sort. UNIT – V Introduction to c++ programming-object oriented programming concepts, Structured Vs OOP. Classes and objects-class definition, Objects, class scope and accessing members, Constructors- default constructor, parameterized constructor, constructor initialization list, copy constructor. Destructors. UNIT – VI Static class members, this pointer, friend functions, Dynamic memory management with operators new and delete.Overloading-function overloading, Operator overloading, restrictions on operator overloading, overloading unary and binary operators,templates, inheritance.
  • 2. • Code: 121CS71 DATASTRUCTURES AND C++ LAB (Common to all Branches) 1.Write a C program that implement stack and its operations using arrays 2. Write a C program that implement Queue and its operations using arrays. 3. Write a C program that uses Stack operations to perform the following i) Converting infix expression into postfix expression ii) Evaluating the postfix expression 4. Write a C program that uses functions to perform the following operations on singly linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal 5. Write a C program that uses functions to perform the following operations on doubly linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways 6 Write a C program that uses functions to perform the following: i) Creating a Binary Tree of integers ii) Traversing the above binary tree in preorder, in order and post order. 7. Write C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers : i) Linear search ii) Binary search 8. Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Bubble sort ii) Quick sort 9. Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i)Insertion sort ii) Merge sort iii) Selection Sort 10. Write a C++ program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a,b,c and use the quadratic formula. If the descremainant b2-4ac is negative, display a message stating that there are no real solutions. 11. A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0 and Subsequent terms are found by adding the preceding two terms in the sequence. Write a C++ program to generate the first n terms of the sequence. 12. Write a C++ program that checks whether a given string is palindrome or not.
  • 3. UNIT-I  Topics to be covered  1.Introduction to data structures.  2. Abstract data type (ADT)  3. Stacks and queues  4. Circular queues and their implementation with arrays.  5. Stack applications: 5.1. infix to post fix conversion 5.2. postfix expression evaluation.  6. Applications of queues
  • 4. Introduction to data structures Data- it is a collection of items or values Type- it is a collection of values. ex- integer- 0 to 9 boolean- true or false Data type- it is a data of type and together with the set of operations used to apply on the type. ex- integer is a member of type integer and its operations are addition, subtraction etc…
  • 5. 1.Introduction to data structures.  Definition:- A data structure is an arrangement of data in a computers memory or even on disk storage. It has a different way of storing and organizing (accessing) data in a computer.  Objective of data structure:- manipulation of real-life data requires the following essential tasks- 1.storage representation of user data 2. Retrieval of stored data 3. transformation of user data
  • 6. • Mathematical definition of data structure is D=(d,f,a) where D= data structure d= a set of variables (data objects). f= a set of functions a= set of rules to implement the functions.
  • 7. 2. Abstract data type (ADT)  Data structure is implemented around the concept of an abstract data type that defines the data together with the operations.  ADT contains - data - operations - no implementation details.  ADT is also called as user defined data type.  Only tells about what are the data values required and what operations performed on those objects.
  • 8. Overview of data structures Several data structures are available in the computer science and used based on their applications. Data structures are classified into different types. Data structure Linear ds Non Linear ds Array s Linked list stack queue s Tree s Graph s
  • 9. 1.Linear data structure- all the elements are stored in sequential order or linear order means that all the elements are adjacent to each other. Each element has exactly two neighbors. Predecessor and successor. • the first element does not have predecessor • The last element does not have successor. 2. Non linear data structure- no such sequence in elements, if one element is connected to a more than two adjacent element then it is a non linear data structure.
  • 10. Applications of data structures Implementing data bases of different organizations (ds used is B-Trees) Implement compilers for different languages (ds used is hash tables). Used in every program and software system.
  • 11. 3. Stacks and queues Definition - A stack is an ordered collection of homogeneous data elements, where the insertion and deletion takes place at one end, known as TOP.  The stack is also called LAST IN FIRST OUT(LIFO)  It means: the element which is inserted last must be deleted first  Example 1. No of plates in cafeteria 2. stack of coins
  • 12.  Stack maintains a pointer called top, which keeps trackStack maintains a pointer called top, which keeps track of the top most element in the stack.of the top most element in the stack.  Any insertions or deletions should be based upon theAny insertions or deletions should be based upon the value of top.value of top.  It works on the basis of LIFO (Last in First out).It works on the basis of LIFO (Last in First out).  According to the definition, new elements are insertedAccording to the definition, new elements are inserted from top and the elements are deleted from same endfrom top and the elements are deleted from same end i.e again top.i.e again top.  This suggests that the element inserted most recentlyThis suggests that the element inserted most recently can only be deleted.can only be deleted.  In the stack, the elements are removed in the reverseIn the stack, the elements are removed in the reverse order of that in which they were added to the stack i.eorder of that in which they were added to the stack i.e last element inserted is to be deleted first.last element inserted is to be deleted first.  So it is called last in first out.So it is called last in first out.  Stack has structured with two operationsStack has structured with two operations 1.1. push- insertion adding elements on to a stackpush- insertion adding elements on to a stack 2.2. Pop- deletion removing element from the stackPop- deletion removing element from the stack
  • 13. Basic operations:Basic operations: The basic operations are insertion, deletionThe basic operations are insertion, deletion ,display.,display. In stacks, special terms are given for insertIn stacks, special terms are given for insert and delete. i.e push for insert and pop is forand delete. i.e push for insert and pop is for delete.delete. Push: inserting or adding element into thePush: inserting or adding element into the stack is called push.stack is called push. Pop: deleting or removing element from thePop: deleting or removing element from the stack is called pop.stack is called pop.
  • 14. Elements are inserted in the order as A,B,C,D,EElements are inserted in the order as A,B,C,D,E It represents the stack of 5 elements.It represents the stack of 5 elements. The top most element in the stack is EThe top most element in the stack is E If we want to delete element E has to be deleted firstIf we want to delete element E has to be deleted first
  • 15. Pop operation- delete element from the stack
  • 17. ADT For Stack ADT for stack struct stack { int stack[5],top; } void push(); void pop(); void display();
  • 18. Implementing stack usingImplementing stack using arraysarrays Algorithm for inserting element into the stack:Algorithm for inserting element into the stack: Algorithm push()Algorithm push() 1. if top=(SIZE-1)1. if top=(SIZE-1) then write (‘stack overflow’)then write (‘stack overflow’) elseelse 2. read item or data2. read item or data 3. top3. top top+1←top+1← 4. stack[top] item←4. stack[top] item← 5. stop5. stop
  • 19. Explanation:Explanation:  The stack is of size max. This procedure inserts an elementThe stack is of size max. This procedure inserts an element item on to the top of a stack which is represented by anitem on to the top of a stack which is represented by an array stack.array stack.  The first step of this algorithm checks for an overflowThe first step of this algorithm checks for an overflow condition.condition.  Overflow means inserting element into a stack which isOverflow means inserting element into a stack which is full.full.  If the top value reaches to maximum size of the stack thenIf the top value reaches to maximum size of the stack then elements cannot be inserted into the stack i.e. stack is full.elements cannot be inserted into the stack i.e. stack is full.  Otherwise top is incremented by one and element isOtherwise top is incremented by one and element is inserted into the stack.inserted into the stack.
  • 20. Algorithm to delete elements from the stack:Algorithm to delete elements from the stack: Algorithm pop()Algorithm pop() 1. if top=-11. if top=-1 then write (‘stack underflow’)then write (‘stack underflow’) elseelse 2. item2. item ← stack[top]← stack[top] 3. top ← top-13. top ← top-1
  • 21. Explanation:Explanation: This procedure deletes an element from the stack.This procedure deletes an element from the stack. The first step of this algorithm checks forThe first step of this algorithm checks for underflow condition.underflow condition. If the top value is -1 then stack is empty.If the top value is -1 then stack is empty. Empty stack is known as underflow.Empty stack is known as underflow. Takeout the element from the location where, theTakeout the element from the location where, the top is pointing and then decrement top by one.top is pointing and then decrement top by one.
  • 22. Display of stack:Display of stack: Printing the contents of stack after push and popPrinting the contents of stack after push and pop operations.operations. Algorithm print()Algorithm print() 1. if top=-11. if top=-1 then write (‘stack empty’)then write (‘stack empty’) 2. Repeat for i2. Repeat for i ← top to 0← top to 0 print(stack[i])print(stack[i]) 3. stop3. stop
  • 23.  A queue is a linear data structure in which insertion take place from oneA queue is a linear data structure in which insertion take place from one end calledend called rear endrear end and deletions take place from other end calledand deletions take place from other end called frontfront endend i.e insertion and deletion take place from different ends.i.e insertion and deletion take place from different ends.  The principle used to in queue isThe principle used to in queue is FIFO.(First In First Out)FIFO.(First In First Out)  FIFOFIFO- the element which is inserted First must be deleted First.- the element which is inserted First must be deleted First.  In a queue there are two variables one is theIn a queue there are two variables one is the rearrear and other one isand other one is frontfront..  the element must be alwaysthe element must be always added at rearadded at rear end andend and removed from theremoved from the frontfront.. Basic operations on queue:Basic operations on queue: The operations that can be performed on queue areThe operations that can be performed on queue are  Insertion EnqueueInsertion Enqueue  Deletion DequeueDeletion Dequeue  DisplayDisplay QueuesQueues Front rear
  • 28. FrontRear Front Rear Front Rear •A queue is like a line of people waiting forA queue is like a line of people waiting for • a bank teller. The queue has aa bank teller. The queue has a frontfront and aand a rearrear.. New people must enter the queue at the rear.New people must enter the queue at the rear. When an item is taken from the queue, it always comes from the front.When an item is taken from the queue, it always comes from the front.
  • 29. • Different types of queues 1. Linear queue or queue 2. Circular queue 3. Doubly ended queue( dequeue) 4. Priority queue
  • 30. This type of data structure is used in timeThis type of data structure is used in time sharing systems where many user jobs will besharing systems where many user jobs will be waiting in the system queue for processing.waiting in the system queue for processing. These jobs may request the services of CPU,These jobs may request the services of CPU, main memory or external devices such asmain memory or external devices such as printer.printer.
  • 31. Working of a linear queue:- i) Initially front=rear= -1. It indicates queue is empty. 0 1 2 3 4 front=rear=-1 0 1 2 3 4 ii) Add 10 10 front rear 0 2 3 4 iii) Add 20 front rear 1 10 20 0 2 3 4 iv) Add 30 front rear 1 10 20 30 0 2 3 4 v) Add 40 front rear 1 10 20 30 40
  • 32. 0 2 3 4 vi) Add 50 front rear 1 10 20 30 40 50 0 2 3 4 vii) Add 60 (overflow) front rear 1 10 20 30 40 50 0 2 3 4 viii) delete (10 is removed) front rear 1 20 30 40 50 0 front rear 1 30 40 50 ix) delete (20 is removed) 2 3 4
  • 33. 0 front rear 1 40 50 x) delete (30 is removed) 2 3 4 0 front rear 1 50 xi) delete (40 is removed) 2 3 4 0 front=rear=-1 1 ix) delete (underflow) 2 3 40 front=rear=-1 1 xii) delete (50 is removed) 2 3 4
  • 34. Implementation of queue usingImplementation of queue using arrayarray Algorithm insert( )Algorithm insert( ) 1.1. If rearIf rear ≥≥ size-1size-1 then write (‘overflow’)then write (‘overflow’) 2.2. Read itemRead item 3.3. rearrear←← rear + 1rear + 1 4.4. queue[rear]queue[rear]←← itemitem 5.5. If(front==-1)If(front==-1) 6.6. front++;front++; 7.7. stopstop Explanation:Explanation: This procedure adds an element item to theThis procedure adds an element item to the queue.queue. First it checks for an overflow condition.First it checks for an overflow condition. If the rear value reaches or exceeds size of thIf the rear value reaches or exceeds size of th queuequeue then elements cannot be inserted into the queuethen elements cannot be inserted into the queue ie. Overflow.ie. Overflow. Whenever element is inserted into the queue,Whenever element is inserted into the queue, rear is increment by onerear is increment by one and place the element in the locationand place the element in the location where rear is pointing.where rear is pointing.
  • 35. Algorithm to delete element from the queueAlgorithm to delete element from the queue Algorithm delete()Algorithm delete() 1.1. If (front= = -1)or (front> rear)If (front= = -1)or (front> rear) then write (‘queue underflow’)then write (‘queue underflow’) itemitem ←← queue [front]queue [front] 2. front2. front ←← front + 1front + 1 Explanation:Explanation: This procedure deletes an element from the queue.This procedure deletes an element from the queue. The first step of this algorithm checks for underflow condition.The first step of this algorithm checks for underflow condition. If the front value is -1or greater than rear then queue is empty.If the front value is -1or greater than rear then queue is empty. Take out the element from the location where, the front is pointing andTake out the element from the location where, the front is pointing and store it in the variable, then increment front by one.store it in the variable, then increment front by one.
  • 36. Algorithm to display elements in a queueAlgorithm to display elements in a queue 1.1. if((front==-1)||(front>rear))if((front==-1)||(front>rear)) 1.1 print statck is Underflow1.1 print statck is Underflow 2. Else2. Else 2.1 repeat for i->front to rear2.1 repeat for i->front to rear 2.2. print queue[i];2.2. print queue[i]; Drawback in queue In a queue when the rear pointer reaches to the end of the queue, insertion would be denied even if room is available at the front one way to remove this is using the circular queue
  • 37. Program: implementation of queue using array # include <stdio.h> # define size 4 void insertion(); void deletion(); void display(); int front=-1,rear=-1,item,choice,queue[size]; void main() {clrscr(); while(1) { printf("n*** MENU ***n 1. INSERTIONn 2. DELETIONn 3.TRAVERSEn 4. EXITn"); printf("enter your choice:"); scanf("%d",&choice); switch(choice) { case 1:insertion(); break; case 2:deletion(); break; case 3:display(); break; case 4:exit();
  • 38. void insertion() { if(rear>=size-1) printf("*** queue is full ***n"); else { printf("enter item into queue:"); scanf("%d",&item); rear++; queue[rear]=item; if(front==-1) front++; } } void deletion() { if((front==-1)||(front>rear)) printf("*** queue is empty ***n"); else { item=queue[front]; front++; printf("the deleted item from queue is %dn",item); } } void display(){ int i; if((front==-1)||(front>rear)) printf("*** queue is empty ***n"); else { printf("n elements in queue:- "); for(i=front;i<=rear;i++) printf("%d ",queue[i]); }}
  • 39. EMPTY QUEUE Circular queues Q[0] Q[1] Q[2] Q[3] Q[N] Delete element 5
  • 40. rear
  • 41. • How to test whether circular queue is empty or full? • The circular q is controlled by the MOD operation. • Circular queue is empty when front =-1 rear=-1 Circular queue is full front = (rear+1)% SIZE
  • 42. Implementation of circular queue using array • Algorithm for insertion 1.if((front == 0 && rear == SIZE-1) || (front == (rear+1)%size) 2.printf("Queue Overflow n"); return; 3.if (front == -1) /*If queue is empty */ 3.1 front = 0; 3.2 rear = 0; 4.else 5.if(rear == SIZE-1)/*rear is at last position of queue */ 6.rear = 0; 7. else 8.rear = rear+1; 9.Read item 10.cq[rear] = item ; 11.end
  • 43. • Algorithm for deletion • 1.if (front == -1) 2.printf("Queue Underflown") return 3.if(front == rear) /* queue has only one element */ 3.1front = -1; 3.2rear=-1; 4.else 5.if(front == SIZE-1) • front = 0; 6.else 7.front = front+1; 8.Stop
  • 44. int insert(){ int item; if((front == 0 && rear == SIZE-1) || (front == rear+1)) { printf("Queue Overflow n"); return;} if (front == -1) /*If queue is empty */ { front = 0; rear = 0; } else if(rear == SIZE-1)/*rear is at last position of queue */ rear = 0; else rear = rear+1; printf("Input the element for insertion in queue : "); scanf("%d", &item); cq[rear] = item ; printf("the element %d at %d position and front= %d,rear=%dn",cq[rear],rear,front,rear); return; }/*End of insert()*/
  • 45. int del() { if (front == -1) { printf("Queue Underflown"); return ; } printf("Element deleted from queue is : %dn",cq[front]); if(front == rear) /* queue has only one element */ { front = -1; rear=-1; } else if(front == SIZE-1) front = 0; else front = front+1; printf("front=%d,rear= %dn",front,rear); return; }/*End of del() */ Deletion
  • 46. display() int display(){ int front_pos = front,rear_pos = rear; if(front == -1){ printf("Queue is emptyn"); Return;} printf("Queue elements :n"); if( front_pos <= rear_pos ) while(front_pos <= rear_pos){ printf("%d ",cq[front_pos]); front_pos++;} else{ while(front_pos <= SIZE-1){ printf("%d ",cq[front_pos]); front_pos++;} front_pos = 0; while(front_pos <= rear_pos){ printf("%d ",cq[front_pos]); front_pos++;}}/*End of else */ printf("n"); return; }/*End of display() */
  • 47. Applications of queues There are several applications of queues in computer science. 1. Implement various aspects of operating systems. 2. CPU scheduling in Multiprogramming environment- single CPU has to serve more than one program simultaneously. 3. Round Robin CPU scheduling algorithm. 4. In operating System maintains a queue of processes that are ready to process or that are waiting for particular event to occur. 5. Computer system maintains a buffer and is implemented as a queue. 6. Printer 7. Call waiting when you are attending other call 8. a file server in a computer network handles file access request from many clients throughout the network. Servers have a limited capacity to service request from clients. when that capacity is exceeded, client requests wait in queues 9. This type of data structure is used in time sharing systems where many9. This type of data structure is used in time sharing systems where many user jobs will be waiting in the system queue for processing. Theseuser jobs will be waiting in the system queue for processing. These jobs may request the services of CPU, main memory or externaljobs may request the services of CPU, main memory or external devices such as printer.devices such as printer.
  • 48. Circular queue using array # include<stdio.h> #include<stdlib.h> # define SIZE 4 int insert(); int del(); int display(); int cq[SIZE]; int front = -1; int rear = -1; main(){ while(1){ printf("1.Insertn"); printf("2.Deleten"); printf("3.Displayn"); printf("4.Quitn"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1 : insert(); break; case 2 : del(); break; case 3: display(); break; case 4: exit(0); default: printf("Wrong choicen"); }/*End of switch*/ }/*End of while */ }/*End of main()*/
  • 49. int insert(){ int item; if((front == 0 && rear == SIZE-1) || (front == rear+1)) { printf("Queue Overflow n"); return;} if (front == -1) /*If queue is empty */ { front = 0; rear = 0; } else if(rear == SIZE-1)/*rear is at last position of queue */ rear = 0; else rear = rear+1; printf("Input the element for insertion in queue : "); scanf("%d", &item); cq[rear] = item ; printf("the element %d at %d position and front= %d,rear=%dn",cq[rear],rear,front,rear); return; }/*End of insert()*/
  • 50. example 1.encq(A) 2.encq(B) 3.encq(c ) 4. Encq ( D ) 5.Decq 6.encq(E) 7. Decq 8.encq( F) 9.Decq 10. Decq 11.Decq 12. Decq
  • 51. Applications of stacksApplications of stacks Parenthesis matching.Parenthesis matching. Evaluation of postfix expressions.Evaluation of postfix expressions. Infix to prefix conversions.Infix to prefix conversions. Infix to postfix conversions.Infix to postfix conversions. Recursion.Recursion. Quick sort.Quick sort.
  • 52. 1.Parenthesis matching1.Parenthesis matching The objective of this function is to check theThe objective of this function is to check the matching of parenthesis in an expressionmatching of parenthesis in an expression i.ei.e  In an expression the no of left parenthesis mustIn an expression the no of left parenthesis must be equal to no: of right parenthesis.be equal to no: of right parenthesis. Ex:Ex: ((A+B)*C)((A+B)*C) This is a valid expression because in this no ofThis is a valid expression because in this no of left parenthesis (2) = no: of right parenthesis (2).left parenthesis (2) = no: of right parenthesis (2).
  • 53. Conversion of expressionsConversion of expressions Arithmetic expressions can be represented in three ways:Arithmetic expressions can be represented in three ways:  Infix notationInfix notation  Prefix notationPrefix notation  Postfix notationPostfix notation 1. Infix notation- In which operator should be placed in between the two operands. Example- A+B C-D E*F G/H. 2. Prefix notation (polish notation)- • Operator preceded by the operand is called prefix notation Examples +AB -CD *EF GH. 3. Postfix notation(reverse polish notation or suffix notation)- • Operator should be placed after operands. AB+ CD- EF* GH
  • 54. Notations – Conversions Consider the infix expression: 2 + 3 * (5 – 7) / 9 Let us insert implicit parentheses (2 + ((3 * (5 – 7)) / 9)) Transfer the operators to the beginning of parentheses (+ 2 (/ (* 3 (– 5 7)) 9)) Remove the parentheses: + 2 / * 3 – 5 7 9 This is the equivalent prefix expression. Transfer the operators to the end of parentheses (2 ((3 (5 7 –) *) 9 /) +) Remove the parentheses: 2 3 5 7 – * 9 / + This is the equivalent postfix expression.
  • 55. Examples Infix Expression Prefix Expression Postfix Expression 2 + 3 + 2 3 2 3 + 2 + 3 * 5 + 2 * 3 5 2 3 5 * + (2 + 3) * 5 * + 2 3 5 2 3 + 5 * 2 * 3 – (5 + 9) – * 2 3 + 5 9 2 3 * 5 9 + –
  • 56. Infix to post fix(RPN) Conversion Algorithm to convert infix expression to RPN: 1. Declare a stack. 2. Repeat the following steps until the end of the infix expression is reached. 1. Get input token (constant, variable, arithmetic operator, left parenthesis, right parenthesis) in the infix expression. 2. If the token is 1. A left parenthesis: Push it onto the stack. 2. A right parenthesis: 1. Pop and display stack elements until a left parenthesis is on the top of the stack. 2. Pop the left parenthesis also, but do not display it. 3. An operator: 1. While the stack is nonempty and token has lower or equal priority than stack top element, pop and display. 2. Push token onto the stack. 4. An operand: Display it. 3. When the end of the infix expression is reached, pop and display stack items until the stack is empty.
  • 57. Note • 1. the lower precedence operator never placed on top of the higher precedence.
  • 59. Infix expression- (A+B)^C-(D*E)/F Infix Stack Post fix ( ( Empty A ( A + (+ A B (+ AB ) Empty AB+ ^ ^ AB+ C ^ AB+C - - AB+C^ ( -( AB+C^ D -( AB+C^D * -(* AB+C^D E -(* AB+C^DE ) - AB+C^DE* / -/ AB+C^DE* F -/ AB+C^DE*F Empty AB+C^DE*F/-
  • 60. Postfix (reverse polish notation) expression evaluation • Algorithm 1.Scan expression from left to right and repeat steps 2 and 3 for each element of expression. 2. If an operand is encountered, put it on stack. 3.If an operator op1 is encountered then 3.1 remove the top two elements of stack, where A is the top and B is the next top element. 3.2 evaluate B op1 A 3.3 push the result back on to the stack. 4. set the top value on stack. 5. stop
  • 61. Evaluate the expression • Postfix:- 5,6,2,+,*,12,4,/,- Symbol scanned stack content 5 5 6 5 6 2 5 6 2 + 5 8 * 40 12 40 12 4 40 12 4 / 40 3
  • 62. Convert infix to postfix expression 1. (A-B)*(D/E) 2. (A+B^D)/(E-F)+G 3. A*(B+D)/E-F*(G+H/K) 4. ((A+B)*D)^(E-F) 5. (A-B)/((D+E)*F) 6. ((A+B)/D)^((E-F)*G) 7. 12/(7-3)+2*(1+5) 8. 5+3^2-8/4*3+6 9. 6+2^3+9/3-4*5 10. 6+2^3^2-4*5 Evaluate the postfix expression 1. 5,3,+,2,*,6,9,7,-,/,- 2. 3,5,+,6,4,-,*,4,1,-,2,^,+ 3. 3,1,+,2,^7,4,1,-,2,*,+,5.-
  • 63. #include<stdio.h> #include<ctype.h> #include<string.h> int priority(char c); int push(char c); int pop(); static char str[30]; int top=-1; void main() { char in[30],post[30],ch; int i,j,l; printf("enter the string"); gets(in); l=strlen(in); Write a C program to convert infix to postfix evaluation
  • 64. for(i=0,j=0;i<l;i++){ if(isalpha(in[i])) post[j++]=in[i]; else { if(in[i]=='(') push(in[i]); else if(in[i]==')') while((ch=pop())!='(') post[j++]=ch; else { while(priority(in[i])<=priority(str[top])) post[j++]=pop(); push(in[i]); }}}while(top!=-1) post[j++]=pop(); post[j]='0'; printf("n equivalent infix to postfix is: %s",post); } int priority (char c) { switch(c) { case'+': case'-': return 1; case'*': case'/': return 2; case'$':return 3; case '^':return 4; } return 0; } int push(char c) {str[++top]=c; } pop() { return(str[top--]); }

Notas del editor

  1. When you think of a computer science queue, you can imagine a line of people waiting for a teller in a bank. The line has a front (the next person to be served) and a rear (the last person to arrive.