DS Unit 1
DS Unit 1
2
Data can be represented in the form of binary digits in memory. A
binary digit can be stored using the basic unit of data called bit. A
bit
can represent either a zero or a one.
3
The main objective of the data structure is to store and
retrieve the data in effectively and efficiently.
D= data structure
d= a set of variables (data objects)
f= a set of functions
a= set of rules to implement the functions.
4
Classification 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.
Type
s
5
• Linear Data Structures: A data structure is said to be linear
if its elements form a sequence or a linear list.
6
Abstract Data Type (ADT)
Abstract Data Type is a
Declaration of data and
Declaration of operations.
struct stack
{
int top, size;
};
void push();
void pop();
void display();
8
Stacks
A stack is a Last In First Out (LIFO) data structure in which all
insertions and deletions are takes place at one end, called the top.
Stack maintains a variable called top, which keeps track of the top
most element in the stack.
In the stack, the elements are removed in the reverse order of that in
which they were added to the stack that is last element inserted is
to be deleted first.
Basic Stack Operations:
push/insert : To insert an item into stack
pop/delete : To delete an item from stack
traverse/display : To display an items
isFull : To know whether the stack is full or not
isEmpty : To know whether the stack is empty or not
9
A stack of cups
A stack of coins
10
Example 1:
When the elements are inserted in the order as A,B,C,D then the size
of the stack is 4 and the top most element in the stack is D.
When deletion operation is performed on stack continuously then the
order in which the elements are deleted is D,C,B,A.
D to
C to C p
B to B p B
A to A p A
p A
C to
p B to
B
p
A A A to
p
11
Example 2: Here Stack Size is
4
3 3 3
2 2 2
1 1 TOP-> 1 20
0 TOP-> 0 10 0 10
TOP-> 3 40 TOP-> 3 40
3
TOP-> 2 2 30 2 30
30
1 20 1 20
1 20
0 10 0 10
0 10
Push 40 Push 50
Push 30
(Overflow)
12
3 3
TOP-> 2 30 2
1 20 TOP-> 1 20
0 10 0 10
pop pop
3 3
2
2
1 1
TOP-> 0 0
10
pop (TOP = -1)
pop underflow
13
Example:3
14
Example 4:
15
Implementing Stack using Array
Procedure:
A top is an integer value, which contains the array index for the
top of
the stack.
If the top value reaches to maximum size of the stack then items cannot
be inserted into the stack i.e. stack is full.
Otherwise top is incremented by one and item is inserted into the stack.
17
Algorithm for deleting an element from the stack
Algorithm pop()
1. if top = -1 then
print “stack is empty”
2. else
1. item = stack[top]
2. top=top-1
3.endif
4.stop
Algorithm display()
1. if top = -1
1.print “stack empty”
2. else
1. for(i = top; i >= 0;i--)
1.print “stack[i]”
3.endif
4. stop
19
/*Week-1
Write a C program that implement stack and its operation by using the
arrays
Description:
In this program we have to implement the stack operation by using the
arrays. Here the stack operations are push and pop. Push operation is used
to insert the elements into a stack and pop operation is used to remove the
elements from the a stack
Program*/
# include <stdio.h>
# define SIZE 4
void push();
void pop();
void display();
int isEmpty();
int isFull();
int top=-1,stack[SIZE],item,choice;
void main(){
while(1){
printf(" *** MENU ***\n 1. PUSH\n 2. POP\n 3.DISPLAY\n 4.isEmpty\n 5.isFull\n 6.EXIT\n");
printf("enter your choice from menu:");
scanf("%d",&choice);
switch(choice){
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:isEmpty();
break;
case 5:isFull();
break;
case 6:exit();
default:printf("wrong choice\n");
}//switch
}//while
}
void push(){
if(top==size-1)
printf("*** stack overflow(full) ***\n");
else
{
printf("enter the item to be pushed into the stack:");
scanf("%d",&item);
top++;
stack[top]=item;
}
}
void pop(){
if(top==-1)
printf("*** stack is empty ***\n");
else
{
item=stack[top];
top--;
printf("the deleted item from stack
is %d\n",item);
}
void display(){
int i;
if(top==-1)
printf("**** stack
underflow****");
else
{
printf("*** stack display ***\n");
for(i=top;i>=0;i--)
if(i==top)
printf("%d at %d
->top\n",stack[i],i);
else
printf("%d at %d\
n",stack[i],i);
}
}
int isEmpty(){
if(top==-1)
printf("stack is
empty");
else
int isFull()
{
if(top==size-1)
printf("stack is full");
else
printf("stack is not full");
return 0;
}
Applications of Stack
25
Reversing an array of elements
Very easy application is to reverse the order of a given array of items.
Algorithm reverse(string)
1. Initialize an empty stack.
2. while not the end of string
2.1 read a character
2.2 push it on to the stack
3. end while
4.while the stack is nonempty
4.1 pop a character
4.2 print it
5.end while
26
Types of expressions
Arithmetic expressions can be represented in three ways:
2+3
2+3*5
(2 + 3) * 5
2 * 3 – (5 + 9)
29
2.INFIX TO RPN CONVERSION
Algorithm to convert infix expression to RPN:
1. Initialize an empty stack.
2. Repeat the following until the end of the infix expression is reached.
1. Get next 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: Left parenthesis in the stack has lowest priority)
An Example: 3*(9-2)+5
Remaining Infix String Stack Postfix String
*(9-2)+5 empty 3
(9-2)+5 * 3
9-2)+5 *( 3
-2)+5 *( 39
2)+5 *(- 39
+5 * 392-
5 + 392-*
null + 392-*5
31 null + 392-*5+
INFIX TO RPN CONVERSION – DEMO
Expression: Output:
3 ( 9 – 2 ) + 5 1. Scan a token.
*
1. 3 is an operand.
2. Display 3.
S 2. Scan next token.
C 1. * is an operator.
A 2. Push * onto stack.
N 3. Scan next token.
1. ( --- left parenthesis.
2. Push ( onto stack.
4. Scan next token.
1. 9 is an operand.
2. Display 9.
5. Scan next token.
1. – is an operator.
2. Priority > that of (.
3. Push – .
6. Scan next token.
1. 2 is an operand.
2. Display 2.
7. Scan next token.
1. ) --- right parenthesis.
DEMO
Expression: Output: 3 9 2 –
*
An Example: 7-(2*3+5)*(8-4/2) 723*5+842/-*-
Remaining Infix String Stack Postfix String
7-(2*3+5)*(8-4/2) empty null
-(2*3+5)*(8-4/2) empty 7
(2*3+5)*(8-4/2) - 7
2*3+5)*(8-4/2) -( 7
*3+5)*(8-4/2) -( 72
3+5)*(8-4/2) -(* 72
+5)*(8-4/2) -(* 723
5)*(8-4/2) -(+ 723*
)*(8-4/2) -(+ 723*5
*(8-4/2) - 723*5+
(8-4/2) -* 723*5+
8-4/2) -*( 723*5+
-4/2) -*( 723*5+8
4/2) -*(- 723*5+8
/2) -*(- 723*5+84
2) -*(-/ 723*5+84
) -*(-/ 723*5+842
34
null empty 723*5+842/-*-
/*3i).Write a C program that uses stack operations to perform convertion of infix expression into
postfix expression.*/ for(i=0,j=0;i<l;i++)
#include<stdio.h> {
#include<ctype.h> if(isalpha(in[i]) || isdigit(in[i]))
#include<string.h> post[j+
static char stack[30]; +]=in[i];
int top=-1; else {
int push(char);
if(in[i]=='(')
char pop();
int priority(char); push(in[i]);
void main() else
{
char in[30],post[30],ch; if(in[i]==')') {
int i,j,l;
printf("\n Enter the string(Infix Expression): "); while((ch=pop())!='(')
gets(in);
post[j++]=ch;
l=strlen(in);
}
printf("\n The length of the given string is: %d\n",l);
else
{
while(priority(in[i])<=priority(sta
ck[top]))
post[j++]=pop();
35
push(in[i]);
while(top!=-1)
post[j++]=pop();
post[j]='\0';
printf("\nEquivalent infix to postfix is:%s ",post);
}//main
int priority (char c) {
switch(c) {
case '+':
case '-': return
1;
case '*':
case '/': return
2;
case '$': return
3;
case '^': return
4;
}//switch
return 0;c) {
int push(char
}//priority
stack[++top]=c;
return 0;
}//push
char pop(){
return (stack[top--]);
}//pop
36
3.EVALUATION OF RPN EXPRESSION
Algorithm evaluateRPN(expression)
1.Initialize an empty stack.
2.Do
1. Get next token (constant, variable, arithmetic operator) in
RPN expression.
2. If token is an operand, push it on the stack.
3. If token is an operator do the following:
1. Pop top two values from the stack. (If the stack does not contain
two items, report error.)
2. Apply operator token to these two values.
3. Push the resulting value onto the stack.
3.Until the end of the expression is encountered.
4.The value of the expression is on the top of the stack
(and stack should contain only this value).
– DEMO
Expression:
1. Scan a token.
2 4 * 9 5 + – 1. 2 is an operand.
2. Push 2 onto stack.
S 2. Scan next token.
C 1. 4 is an operand.
A 2. Push 4 onto stack
N 8 3. Scan next token.
1. * is an operator.
2. Pop from stack --- 4.
3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 8 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
Top
EXPRESSION – DEMO
Expression: 1. Scan a token.
5 + – 1. 2 is an operand.
2. Push 2 onto stack.
2. Scan next token.
S 1. 4 is an operand.
C 2. Push 4 onto stack
A 3. Scan next token.
N 14 1. * is an operator.
2. Pop from stack --- 4.
3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 6 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
5. Scan next token.
1. 5 is an operand.
2. Push 5 onto stack.
6. Scan next token.
1. + is an operator.
Top 2. Pop
3. Pop
9 4. Apply +
5. Push result.
8 7. Scan next token.
1. - is an operand.
EXPRESSION – DEMO
Expression: 1. Scan a token.
– 1. 2 is an operand.
2. Push 2 onto stack.
2. Scan next token.
S 1. 4 is an operand.
C 2. Push 4 onto stack
A 3. Scan next token.
1. * is an operator.
N 2. Pop from stack --- 4.
3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 6 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
5. Scan next token.
1. 5 is an operand.
2. Push 5 onto stack.
6. Scan next token.
1. + is an operator.
2. Pop
3. Pop
Top 4. Apply +
5. Push result.
-6 7. Scan next token.
1. - is an operand.
EXPRESSION – DEMO
1. Scan a token.
Expression: 1. 2 is an operand.
2. Push 2 onto stack.
2. Scan next token.
1. 4 is an operand.
S 2. Push 4 onto stack
3. Scan next token.
C 1. * is an operator.
-6 A 2. Pop from stack --- 4.
N 3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 6 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
5. Scan next token.
1. 5 is an operand.
2. Push 5 onto stack.
6. Scan next token.
1. + is an operator.
2. Pop
3. Pop
4. Apply +
5. Push result.
7. Scan next token.
1. - is an operand.
Top 2. Pop, pop, apply -, push result.
8. Scan next token
1. End of expression
Evaluate the postfix expression: 5 6 2 + * 12 4 / -
Remaining postfix String Symbol Scanned Stack
5 6 2 + * 12 4 / - no symbol empty
6 2 + * 12 4 / - 5 5
2 + * 12 4 / - 6 5
6+ * 12 4 / - 2 5 6 2
* 12 4 / - + 5 8
12 4 / - * 40
4 / - 12 40 12
/ - 4 40 12 4
- / 40 3
null - 37
42
/*3ii).Write a C program that uses Stack operations to perform the evaluation of the
postfix expression*/
#include<stdio.h>
#include<math.h>
void main() {
char postfix[30],t[30];
int stack[10],top=-1,len,i,j,op2,op1,n;
printf("\n\n\nEnter the postfix:");
gets(postfix);
len=strlen(postfix);
postfix[len]=‘#’;
for(i=0;postfix[i]!=‘#’;i++)
{
j=0;
if(postfix[i]==‘ ‘)
continue;
if(postfix[i]=='+'||postfix[i]=='-'||postfix[i]=='*'||postfix[i]=='/'||postfix[i]=='^')
{
op2=stack[top--];
op1=stack[top--];
43
switch(postfix[i]) {
case '+': stack[++top]=op1+op2;
break;
case '-': stack[++top]=op1-op2;
break;
case '*': stack[++top]=op1*op2;
break;
case '/': stack[++top]=op1/op2;
break;
case '^': stack[++top]=pow(op1,op2);
break;
}//end of switch
}//end of if
else {
while(postfix[i]!=‘ ‘) {
t[j++]=postfix[i++];
}
t[j]='\0';
n=atoi(t);
stack[++top]=n;
}
}//end of for
printf("\n\n\nResult=%d\n",stack[top]);
44 }//end of main
Queues
46
Bus Stop Queue
Bus
Stop
47
Bus Stop Queue
Bus
Stop
48
Bus Stop Queue
Bus
Stop
front rear
rear
49
Bus Stop Queue
Bus
Stop
front rear
rear
50
front rear
New people must enter the queue at the
rear.
front
rear
People should leave the queue
from the front end.
rear
front
51
Types of Queues
Linear Queue
Circular Queue
52
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 0 1 2 3 4
10 20 30 40 50 10 20 30 40 50
54
x) delete (30 is removed) xi) delete (40 is removed)
0 1 2 3 4 0 1 2 3 4
40 50 50
0 1 2 3 4 0 1 2 3 4
55
Implementing Queue using Array
Procedure:
56
Algorithm for inserting an element into the queue
Algorithm insert()
Explanation:
1. if rear >= size-1 then This procedure adds an item to the
1. print “queue queue.
is full”
2. exit First it checks for an overflow
2. else condition.
1. if rear = -1 If the rear value reaches or exceeds size
and front = -1 of the queue then elements cannot be
1. inserted into the queue. ie. Queue is full.
front = 0
2. endif Whenever element is inserted into the
queue, rear is increment by one and
3. rear = rear +
place the element in the location where
1
rear is pointing.
4. queue[rear]
= item
57
3. endif
Algorithm for deleting an element from the queue
Explanation:
Algorithm delete() This procedure deletes an element from
the queue.
1. if front = -1 or front >
rear then
The first step of this algorithm checks
1. print “queue for underflow condition.
is empty”
2. exit If the front value is -1 or front > rear
2. else then queue is empty.
1. item = Take out the element from the location
queue[front] where, the front is pointing and store it
2. front = front in the variable, then increment front by
+1 one.
3. endif
4. stop
58
Algorithm for displaying an elements from the queue
Algorithm display()
1. if front = = -1 or front >
rear then
1. print “queue is
empty”
2. exit
2. else
1. for(i = front; i
<= rear; i++)
1. print
“queue[i]”
If the front value 3.
is -1 or front > rear then the queue is empty.
endif
4. stop
If queue is not empty, display the item which is pointed at
queue[front] and increment the front value by one and
repeat this until front <= rear.
59
/*2.Write a C program that implement Queue and its operations using the arrays.
Description:This program implements the Queue operation by using the arrays. Here they Queue operation
are insertion and deletion. insertion operation is used to insert the elements into a Queue and deletion
operation is used to remove the elements from Queue*/
#include<stdio.h>
#include<stdlib.h>
#define size 4
void insertion();
void deletion();
void display();
int front=-1,rear=-1,item,choice,queue[size];
void main(){
while(1){
printf("\n*** MENU ***\n 1. INSERTION\n 2. DELETION\n 3.DISPLAY\n 4. EXIT\n");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice){
case 1 : insertion();
break;
case 2 : deletion();
break;
case 3 : display();
break;
case 4 : exit(0);
default : printf("*** wrong choice ***\n");
}//end of switch
}//end of while
}//end of main
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++;
}//end of else
}//end of insertion
void deletion()
{
if((front==-1)||(front>rear))
printf("*** queue is empty ***\n");
else
{
item=queue[front];
front++;
printf("the deleted item from queue is %d\
n",item);
}//end of else
}//end of delete function
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]);
}//end of else
}//end of display function
/*2. Write a C program that implement Queue and its operations using the arrays*/
#include<stdio.h> #include<stdlib.h> #define size 4
void insertion(); void deletion(); void display();
int front=-1,rear=-1,item,choice,queue[size];
void main() {
while(1) {
printf("\n*** MENU ***\n 1. INSERTION\n 2. DELETION\n 3.TRAVERSE\n 4. EXIT\
n");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice) {
case 1 : insertion();
break;
case 2 : deletion();
break;
case 3 : display();
break;
case 4 : exit(0);
default : printf("*** wrong choice ***\n");
}//switch
}//while
}//main
65
void insertion() {
if(rear>=size-1)
printf("*** queue is full ***\n");
else {
printf("enter item into queue:");
void display() {
scanf("%d",&item);
int i;
rear++;
if((front = = -1)||(front>rear))
queue[rear] = item;
printf("*** queue is empty ***\
if(front = = -1)
n");
front++;
else {
}//else
printf("\n elements in queue:- ");
}//insertion
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
void deletion() {
}//else
if((front = = -1)||(front>rear))
}//display
printf("*** queue is empty ***\n");
else
{
item = queue[front];
front++;
printf("the deleted item from queue is %d\
n",item);
}//else
66 }//deletion
Circular Queue:
A circular queue also have a Front and Rear to keep the track of
elements to be deleted and inserted and therefore to maintain the
unique characteristic of the queue.
67
Circular Queue with size 5 After adding 5, 10, 20
69
Algorithm to Display :
70
/* Program for 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() {
int choice;
while(1) {
printf("1.Insert\n 2.Delete\n 3.Display\n 4.Quit\
n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice) {
case 1 : insert();
break;
case 2 : del();
break;
71 case 3: display();
break;
int insert() {
int item;
if(front == (rear+1)%SIZE) {
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);
72 cq[rear] = item ;
return;
int del()
{
if (front == -1) {
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\
n",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;
return;
}/*End of del() */
73
else
int display()
{
{
while(front_pos <=
int front_pos = front,rear_pos =
SIZE-1)
rear;
{
if(front == -1)
printf("%d
{
",cq[front_pos]);
printf("Queue is empty\
front_pos++;
n");
}
return;
front_pos = 0;
}
while(front_pos <=
rear_pos) {
printf("Queue elements :\n");
printf("%d
",cq[front_pos]);
if( front_pos <= rear_pos )
front_pos++;
while(front_pos <= rear_pos)
}
{
}/*End of else */
printf("%d
",cq[front_pos]);
printf("\n");
front_pos++;
74 return;
}
Applications of Queue
75
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
76
Convert infix to postfix expression
1. (A-B)*(D/E)---AB-DE/*
2. (A+B^D)/(E-F)+G----ABD^+EF-/G+
3. A*(B+D)/E-F*(G+H/K) :-ABD+*E/FGHK/+*-
4. ((A+B)*D)^(E-F):-AB+D*EF-^
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. 53+2*697-/-
2. 35+64-*41–2^+
3. 31+2^741–2*+5-
78