73
PROBLEM: 1(a).Write a C program to demonstrate the working of a stack of size N using array.The elements of the stack may be assumed to be of type integer or real. The operations to be supported are: 1.PUSH 2.POP 3.DISPLAY.The program should print appropriate messages for stack overflow, stack underflow and stack empty. DEFINITION : Lists permits the insertion or deletion of an element to occur only at one end. A linear list belonging to this sub-class is called a stack. They are also referred to as push-down lists or LIFO(Last In First Out)lists. ALGORITHM : STACK Procedure PUSH(S, TOP, X): This procedure inserts an element X to the top of the stack which is represented by a vector S consisting MAX elements with apointer TOP denoting the top element in the stack. STEP 1 : [Check for stack underflow] If (TOP>=max-1) then write(stack overflow) Return STEP 2 : [Increment TOP] TOP TOP+1 STEP 3 : [Insert element] S[TOP] X STEP 4 : [Finished] Return The 1st step of this algorithm checks for an overflow condition.If such a condition exists,then the insertion can't be performed and an appropriate error message results. Procedure POP(S,TOP,X) : This procedure removes top element from the stack. STEP 1 : [Check for the underflow on stack] If (TOP<0) then write(stack underflow) Return STEP 2 : [Hold the former top element of stack into X] X S[TOP] STEP 3 : [Decrement the TOP pointer or index by 1] TOP TOP-1 STEP 4 : [finished-Return the popped item from the stack] Return(X) As Underflow condition is checked for in the first step of the algorithm.If such a condition exists,then the deletion cannot be performed and an appropriate error message results. Procedure Display(S,TOP) : This procedure displays the contents of the stack i.e., vector S. STEP 1 : [check for empty on stack] if (TOP==-1) then write('stack empty') Return Expt No : 1(a) STACK 1

D.S

Embed Size (px)

Citation preview

Page 1: D.S

PROBLEM: 1(a).Write a C program to demonstrate the working of a stack of size N using array.The elements of the stack may be assumed to be of type integer or real. The operations to be supported are: 1.PUSH 2.POP 3.DISPLAY.The program should print appropriate messages for stack overflow, stack underflow and stack empty.

DEFINITION : Lists permits the insertion or deletion of an element to occur only at one end. A linear list belonging to this sub-class is called a stack. They are also referred to as push-down lists or LIFO(Last In First Out)lists.

ALGORITHM : STACKProcedure PUSH(S, TOP, X): This procedure inserts an element X to the top of the stack which is represented by a vector S consisting MAX elements with apointer TOP denoting the top element in the stack.STEP 1 : [Check for stack underflow] If (TOP>=max-1) then write(stack overflow) ReturnSTEP 2 : [Increment TOP] TOP TOP+1STEP 3 : [Insert element] S[TOP] XSTEP 4 : [Finished] ReturnThe 1st step of this algorithm checks for an overflow condition.If such a condition exists,then the insertion can't be performed and an appropriate error message results.

Procedure POP(S,TOP,X) : This procedure removes top element from the stack.STEP 1 : [Check for the underflow on stack] If (TOP<0) then write(stack underflow) ReturnSTEP 2 : [Hold the former top element of stack into X] X S[TOP]STEP 3 : [Decrement the TOP pointer or index by 1] TOP TOP-1STEP 4 : [finished-Return the popped item from the stack] Return(X)As Underflow condition is checked for in the first step of the algorithm.If such a condition exists,then the deletion cannot be performed and an appropriate error message results.

Procedure Display(S,TOP) : This procedure displays the contents of the stack i.e., vector S.STEP 1 : [check for empty on stack] if (TOP==-1) then write('stack empty') ReturnSTEP 2 : [Repeat through STEP 3 from i=TOP to 0] Repeat through STEP 3 for i=TOP to 0 STEP-1]STEP 3 : [Display the stack content] write (S[i])STEP 4 : [Finished] ReturnThe first step of this algorithm checks for an empty condition.If such a condition exists, then the contents of the stack cannot be displayed and an appropriate error message results.

Expt No : 1(a) STACK 1

Page 2: D.S

#include<stdio.h>#define MAX 5int top,stack[MAX];void init(){

top=-1;}void push(int x){

stack[++top]=x;}int pop(){

return(stack[top--]);}void display(){

int i;printf("The stack content is:\n");for(i=top;i>=0;i--)

printf("%d\n",stack[i]);}int overflow(){

if(top>=MAX-1)return 1;

elsereturn 0;

}int underflow(){

if(top<=-1)return 1;

elsereturn 0;

}int empty(){

if(top==-1)return 1;

elsereturn 0;

}main(){

int item,choice;clrscr();init();while(1){

printf("\nMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");printf("Enter your choice\n");scanf("%d",&choice);switch(choice){

case 1:if(overflow())

printf("stack overflow\n");else

Expt No : 1(a) STACK 2

Page 3: D.S

{printf("Enter an element to be inserted\n");scanf("%d",&item);push(item);

}break;

case 2:if(underflow())

printf("stack underflow\n");else

printf("The deleted item is %d\n",pop());break;

case 3:if(empty())

printf("stack is empty\n");else

display();break;

case 4:exit();

default:printf("Invalid choice\n");

}}

}

Expt No : 1(a) STACK 3

Page 4: D.S

PROBLEM : Write a C program to evaluate a valid suffix or postfix expression using Stack. Assume that the suffix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The arithmetic operators allowed are +(ADD), -(SUBTRACT), *(MULTIPLY) and /(DIVIDE).

DEFINITION : The prefixes “pre-“, “post-“ and “in-“ refer to the relative position of the operator with respect to the two operands. In postfix notation, the operator follows the two operands. Consider the sum of A and B, we think of applying the operator “+” to the operands A and B to write the sum as AB+ in postfix notation.

Algorithm : Evaluation of a Postfix or Suffix expression

STEP 1 : Read the given postfix expression into a string called postfix.STEP 2 : Read one character at a time & perform the following

operations:1. If the read character is an operand, then convert it to float and

push it onto the stack.2. If the character is not an operand, then pop the operator from

stack and assign to OP2. Similarly, pop one more operator from stack and assign to OP1.

3. Evaluate the result based on operator x.4. Push the result (based on operator x) onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : Return the result from this procedure or algorithm and display the result in main program.

Expt No : 1(b) STACK – Evaluate Postfix 4

Page 5: D.S

/* PROGRAM TO EVALUATE A POSTFIX EXPRESSION */#include<stdio.h>#include<math.h>#include<stdlib.h>int operand(x){

if (x>='0' && x<='9')return 1;

elsereturn 0;

}float stack[30];char postfix[30];int top = -1;/* FUNCTION TO PUSH AN ITEM ONTO THE STACK */void push(float x){

stack[++top] = x;}/* FUNCTION TO POP AN ELEMENT FROM TOP OF THE STACK */float pop(){

return (stack[top--]);}/* FUNCTION TO CALCULATE RESULT OF OPERATOR PASSED FROM PROCESS */float eval(float x, float y, char opr){

switch(opr){

case '+': return (x + y);case '-': return (x - y);case '*': return (x * y);case '/': return (x / y);case '^': return (pow(x, y));

}}/* FUNCTION TO PROCESS THE POSTFIX EXPRESSION */float process(){

int i,x;//char x;float oprnd1,oprnd2,result;for (i=0; (x = postfix[i])!='\0'; i++)

{if (operand(x))

push((float)(x - '0')); /* TO GET THE EXACT DIGIT TO BE PROCESSED */else

{oprnd2 = pop();oprnd1 = pop();result = eval(oprnd1,oprnd2,x);push(result);

}}

return result;}/* MAIN PROGRAM */main(){

Expt No : 1(b) STACK – Evaluate Postfix 6Expt No : 1(b) STACK – Evaluate Postfix 5

Page 6: D.S

clrscr();printf("Enter a postfix expression :\n");scanf("%[^\n]s",postfix);printf("The result of the given expression is: .3f\n",process());

}

Expt No : 1(b) STACK – Evaluate Postfix 6

Page 7: D.S

PROBLEM : Write a C program to convert and print a given valid fully paranthesized Infix arithmetic expression to Suffix expression. The expression consisting of single character (letter or digit) as operands and +,-,*,/ as operators. You may assume that only binary operators are allowed in the expression.

DEFINITION : The prefixes “pre-“, “post-“ and “in-“ refer to the relative position of the operator with respect to the two operands. In postfix notation, the operator follows the two operands. Consider the sum of A and B, we think of applying the operator “+” to the operands A and B to write the sum as AB+ in postfix notation.

ALGORITHM : Infix to Postfix Expression

STEP 1 : Read the given infix expression into string called infix.STEP 2 : Read one character at a time and perform the following operations :

1. If the read character is an operand, then add the operand to the postfix string.

2. If the read character is not an operand, then check If the stack is not empty and precedence of the top of the stack operator is higher than the read operator, then pop the operator from stack and add this

operator to the postfix string. Else push the operator onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : If stack is not empty, then pop the operator from stack and add this operator to the postfix string.

STEP 5 : Repeat STEP 4 till all the operators are popped from the stack.STEP 6 : Display the result of given infix expression or resultant postfix expression stored in a string called postfix from this algorithm.

Expt No : 2 STACK – Infix to Postfix 7

Page 8: D.S

/* PROGRAM TO CONVERT INFIX EXPRESSION TO POSTFIX EXPRESSION USING STACK */#include<stdio.h>#include<string.h>/* MACRO FUNCTION TO CHECK WHETHER GIVEN CHARACTER IS AN OPERAND OR NOT */#define operand(x) (x>='a' && x<='z' || x>='A' && x<='Z' || x>='0' && x<='9')char infix[30],postfix[30],stack[30];int top,i=0;/* FUNCTION TO INITIALIZE THE STACK */void init(){

top=-1;}/* FUNCTION TO PUSH AN OPERATOR ON TO THE STACK */void push(char x){

stack[++top]=x;}/* FUNCTION TO POP A CHARACTER STORED ONTO THE STACK */char pop(){

return(stack[top--]);}/* FUNCTION TO RETURN IN STACK PRIORITY OF A CHARACTER */int isp(char x){

int y;y=(x=='('?0:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1);return y;

}/* FUNCTION TO RETURN INCOMING CHARACTER'S PRIORITY */int icp(char x){

int y;y=(x=='('?4:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1);return y;

}/* FUNCTION TO CONVERT THE GIVEN INFIX TO PREFIX EXPRESSION */void infixtopostfix(){

int j,l=0;char x,y;stack[++top]='\0';for (j=0; (x=infix[i++])!='\0'; j--)

if (operand(x))postfix[l++]=x;

elseif (x==')')

while ((y=pop())!='(')postfix[l++]=y;

else{

while (isp(stack[top])>=icp(x))postfix[l++]=pop();

push(x);}

while (top>=0)postfix[l++]=pop();

}

Expt No : 2 STACK – Infix to Postfix 7Expt No : 2 STACK – Infix to Postfix 8

Page 9: D.S

/* MAIN PROGRAM */void main(){init();printf("Enter an infix expression :\n");scanf("%s",infix);infixtopostfix();printf("The resulting postfix expression is %s",postfix);}

Expt No : 2 STACK – Infix to Postfix 9

Page 10: D.S

PROBLEM : Write a C program to convert and print a given valid fully paranthesized Infix arithmetic expression to Prefix expression. The expression consisting of single character (letter or digit) as operands and +,-,*,/ as operators. You may assume that the Infix string is read from right to left and that the Prefix string is created from right to left.

DEFINITION : The prefixes “pre-“, “post-“ and “in-“ refer to the relative position of the operator with respect to the two operands. In prefix notation, the operator precedes the two operands. Consider the sum of A and B, we think of applying the operator “+” to the operands A and B to write the sum as +AB in prefix notation.

Algorithm : Infix to Prefix expression.

STEP 1 : Read the given infix expression into string called infix.STEP 2 : Reverse the infix string and read one character at a time and

perform the following operations :3. If the read character is an operand, then add the operand to the

prefix string.4. If the read character is not an operand, then check

If the stack is not empty and precedence of the top of the stack operator is higher than the read operator, then pop the operator from stack and add this

operator to the prefix string. Else push the operator onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : If stack is not empty, then pop the operator from stack and add this operator to the prefix string.

STEP 5 : Repeat STEP 4 till all the operators are popped from the stack.STEP 6 : Reverse the prefix string and display the result of the given infix

expression or the resultant prefix expression stored in a string called prefix from this algorithm.

Expt No : 3 STACK – Infix to Prefix 10

Page 11: D.S

/* PROGRAM TO CONVERT INFIX TO PREFIX EXPRESSION USING STACK */#include<stdio.h>#include<string.h>/*MACRO FUNCTION TO CHECK WHETHER GIVEN CHARACTER IS OPERAND OR NOT */#define operand(x)(x>='a'&&x<='z' || x>='A'&&x<='Z' || x>='0'&&x<='9')char infix[30],prefix[30],stack[30];int top,i=0;/* FUNCTION TO INITIALIZE THE STACK */void init(){

top=-1;}/* FUNCTION TO PUSH AN OPERATOR ON TO THE STACK */void push(char x){

stack[++top]=x;}/* FUNCTION TO POP A CHARACTER STORED ONTO THE STACK */char pop(){

return(stack[top--]);}/* FUNCTION TO RETURN IN STACK PRIORITY OF A CHARACTER */int isp(char x){int y;y=(x=='('?6:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?0:-1);return y;}/* FUNCTION TO RETURN INCOMING CHARACTER'S PRIORITY */int icp(char x){int y;y=(x=='('?6:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?4:-1);return y;}/* FUNCTION TO CONVERT THE GIVEN INFIX TO PREFIX EXPRESSION */void infixtoprefix(){

int j,l=0;char x,y;stack[++top]='\0';for (j=strlen(infix)-1; j>=0; j--)

{x=infix[j];if (operand(x))

prefix[l++]=x;else

if (x=='(')while ((y=pop())!=')')

prefix[l++]=y;else

{while (isp(stack[top])>=icp(x))

prefix[l++]=pop();push(x);

}}

while (top>=0)

Expt No : 3 STACK – Infix to Prefix 11

Page 12: D.S

prefix[l++]=pop();}/* MAIN PROGRAM */void main(){clrscr();init();printf("Enter an infix expression :\n");scanf("%s",infix);infixtoprefix();strrev(prefix);printf("The resulting prefix expression is %s",prefix);}

Expt No : 3 STACK – Infix to Prefix 12

Page 13: D.S

PROBLEM : Write a C program to simulate the working of an ordinary Queue of integers using an array. Provide the following operations : 1. QINSERT 2. QDELETE 3. QDISPLAY. Write functions to check the Queue Status : Qempty, Qfull.

DEFINITION : The lists permits deletions to be performed at one end of a list and insertions at the other. The information in such a list is processed in the same order as it was received, that is on a First Come First Served(FCFS) basis. This type of list is referred to as a queue (FIFO–First In First Out).

ALGORITHM : QUEUEProcedure QINSERT(Q,F,MAX,X) : Given F and R, pointers to the front and rear elements of a queue.A QUEUE Q consisting of MAX elements and an element X. this procedure inserts X at the rear end of the queue prior to the first invocation of the procedure,F and R have been set to -1.STEP 1:[Is front pointer properly set] if (F==R) then F R -1STEP 2:[Check for overflow condition] if (R>=(MAX-1)) then write ('Error : Overflow') ReturnSTEP 3:[Increment rear pointer] R R+1STEP 4:[Insert element] Q[R] X Return

Procedure QDELETE(Q,F,R) : Given F and R,the pointers to the front and rear elements of a queue respectively and the queue Q to which they correspond. This procedure delets and returns the element at the front end of the queue .Here X is a temporary variable.STEP 1:[Check for underflow condition] if (F>=R) then write('Error : Underflow'] ReturnSTEP 2:[Increment the front pointer] F F+1STEP 3:[Delete element] Y Q[F] Return Y

Expt No : 4(a) QUEUE 13

Page 14: D.S

/* PROGRAM TO IMPLEMENT A LINEAR QUEUE USING ARRAY */#include<stdio.h>#include<stdlib.h>#define MAX 5int queue[MAX],front,rear;void init(){

front=rear=-1;}void insert(int x){

queue[++rear]=x;}int delete(){

return(queue[++front]);}int overflow(){

if (rear>=MAX-1)return 1;

elsereturn 0;

}int underflow(){

if (front>=rear)return 1;

elsereturn 0;

}int empty(){

if (front==rear)return 1;

elsereturn 0;

}void display(){

int i;printf("The queue content is :\n");if (front<0)

for (i=0; i<=rear; i++)printf("%d\t",queue[i]);

elseif (front == rear)

printf("No items found");else

for (i=front+1; i<=rear; i++)printf("%d\t",queue[i]);

printf("\n");}void main(){

int item,choice;clrscr();init();while (1)

Expt No : 4(a) QUEUE 14

Page 15: D.S

{printf("\nMENU\n1. INSERT\n2. DELETE\n3. DISPLAY\n4. EXIT\n");printf("\nYour Choice = ");scanf("%d",&choice);switch (choice){

case 1:if (front==rear)

front=rear=-1;if (overflow())

printf("Queue Overflow\n");else

{printf("Enter the element to be inserted : ");scanf("%d",&item);insert(item);display();

}break;

case 2:if (underflow())

printf("Queue underflow\n");else{

printf("The deleted item is : %d\n",delete());display();

}break;

case 3:if (empty())

printf("Queue is empty\n");else

display();break;

case 4:exit(0);

default:printf("Invalid Choice\n");

}}

getch();}

Expt No : 4(a) QUEUE 15

Page 16: D.S

PROBLEM : Write a program to design a Priority Queue which is maintained as a set of Queues (assume a maximum of 3 Queues). The elements are inserted based upon the given priority. For example (3, 34) will be inserted to 3rd Queue with the element value 34. The deletion of an element is to be done starting from the 1st Queue, if it is not empty. In case if it is empty, the elements from the 2nd Queue will be deleted, and so on.

DEFINITION :Priority queue is a special type of data strcutures in which items can be inserted or deleted based on the priority. Different types of priority queues are : 1. Ascending Priority queue2. Descending Priority queue

In an Ascending priority queue, elements can be inserted in any order. But while deleting an element from the queue, remove only the smallest element first. In Descending priority queue, elements can be inserted in any order but while deleting, the largest element is deleted first.

ALGORITHM : PRIORITY QUEUEProcedure PQADD(x,y) : Insert the element y into the desired queue based on priority x.STEP 1: If (x == 1) then goto STEP 2 Else If (x == 2) then goto STEP 3 Else If (x == 3) then goto STEP 4 Else ReturnSTEP 2: if (f1 >= r1) f1 r1 -1 If (r1 >= MAX-1) then Write(‘Overflow’) Else r1 r1+1 Q1[r1] y ReturnSTEP 3: if (f1 >= r1) f1 r1 -1 If (r1 >= MAX-1) then Write(‘Overflow’) Else r1 r1+1 Q1[r1] y ReturnSTEP 4: if (f1 >= r1) f1 r1 -1 If (r1 >= MAX-1) then Write(‘Overflow’) Else r1 r1+1 Q1[r1] y Return

Procedure PQDELETE() : Return the deleted item from this procedure.STEP 1 : if ((f1 >= r1) && (f2 >= r2) && (f3 >= r3)) then return 0;

else if (f1 < r1) then goto STEP 2else if (f2 < r2) then goto STEP 3else then goto STEP 4

STEP 2 : f1 f1+1return (q1[f1]);

STEP 3 : f2 f2+1return (q2[f2]);

STEP 4 : f3 f3+1return (q3[f3]);

Expt No : 4(b) PRIORITY QUEUE 16

Page 17: D.S

#include<stdio.h>#define MAX 5struct pq {

int q1[MAX],q2[MAX],q3[MAX]; }q;int f1,f2,f3,r1,r2,r3;/* FUNCTION TO INITILIZE THE QUEUE POINTERS */void init(){

f1 = f2 = f3 = r1 = r2 = r3 = -1;}/* FUNCTION TO INSERT AN ELEMENT INTO A QUEUE DEPENDING ON PRIORITY

X->PRIORITY AND Y->ELEMENT TO BE INSERTED */void padd(int x, int y){

switch(x){

case 1:if (f1 == r1)f1 = r1 = -1; /* REINITIALIZE THE QUEUE1 */

if (r1 >= MAX-1)printf("\nQ1 Overflow\n");

elseq.q1[++r1] = y;

break;

case 2:if (f2 == r2)f2 = r2 = -1; /* REINITIALIZE THE QUEUE2 */

if (r2 >= MAX-1)printf("\nQ1 Overflow\n");

elseq.q2[++r2] = y;

break;

case 3:if (f3 == r3)f3 = r3 = -1; /* REINITIALIZE THE QUEUE3 */

if (r3 >= MAX-1)printf("\nQ1 Overflow\n");

elseq.q3[++r3] = y;

break;}

}/* DELETE AN ELEMENT FROM QUEUE DEPENDING UPON THE PRIORITY */int pdelete(){

if ((f1 >= r1) && (f2 >= r2) && (f3 >= r3))return 0;

else if (f1 < r1)return (q.q1[++f1]);

else if (f2 < r2)return (q.q2[++f2]);

elsereturn (q.q3[++f3]);

}void display(){

int i;if (f1 >= r1)

printf("\nQ1 is empty");

Expt No : 4(b) PRIORITY QUEUE 17

Page 18: D.S

else{

printf("\nQ1 =>\t");for (i=f1+1; i<=r1; i++)

printf("%d\t",q.q1[i]);}

if (f2 >= r2)printf("\nQ2 is empty");

else{

printf("\nQ2 =>\t");for (i=f2+1; i<=r2; i++)

printf("%d\t",q.q2[i]);}

if (f3 >= r3)printf("\nQ3 is empty");

else{

printf("\nQ3 =>\t");for (i=f3+1; i<=r3; i++)

printf("%d\t",q.q3[i]);}

}void main() /* MAIN PROGRAM */{

int ch,priority,item,z;clrscr();init();while(1){

printf("\nMENU\n1. Insert\n2. Delete\n3. Display\n4. Exit");printf("\n\nYour Choice = ");scanf("%d",&ch);switch(ch){

case 1:printf("\nEnter priority and element : ");scanf("%d%d",&priority,&item);padd(priority,item);break;

case 2:z = pdelete();if (z)

printf("\nDeleted item is %d",z);else

printf("\nError : Underflow");break;

case 3:display();break;

case 4:exit(0);

default:printf("\nInvalid Choice. Try again");

} /* End of Switch */} /* End of While */

}/* End of Main Program */

Expt No : 4(b) PRIORITY QUEUE 18

Page 19: D.S

PROBLEM : Write a C program to stimulate the working of a circular queue of names using an array. Provide the following operations : (1).CQINSERT (2).CQDELETE (3).CQDISPLAY. Write functions to check the pueue status - QEmpty,QFull

DEFINITION : To view the array that holds the queue as a circle rather than as a straight line. That is, we imagine the first element of the array as immediately following its last element. This implies that even if the last element is occupied, a new value can be inserted behind it in the first element of the array as long as that first element is empty. This concept of queue is known as Circular Queue [shown in fig.].

(Initial Condition)Front = rear = -1

Fig: Circular Queue

ALGORITHM : CIRCULAR QUEUE

Procedure CQINSERT(CQ,F,R,MAX,NAME) : Given F and R, pointers to the front and rear elements of a circular queue CQ consisting of MAX elements and an element NAME. This procedure inserts X at the rear end of the queue prior to the first invocation of the procedure,F and R have been set to 1. Here 'temp' is a temporary varible within this procedure.STEP 1 : [Incrementing rear pointer] Temp <- R R (R+1) % MAXSTEP 2 : [Check for overflow condition]

If (R==F) then R temp

write(overflow) ReturnSTEP 3 : [Insert element] Q[R] NAME Return

Procedure CQDELETE(CQ,F,R) : Given F and R, pointer to the front and the queue CQ to which they correspond. This procedure deletes and returns the element at the front-end of the queue.STEP 1 : [Check for underflow condition] if(R==F) then Write('Underflow') ReturnSTEP 2 : [Increment the front pointer] F (F+1)%MAXSTEP 3 : [Delete element]

Write(Q[F])Return

Expt No : 4(b) SINGLY LINKED LIST 9Expt No : 5 CIRCULAR QUEUE 19

Page 20: D.S

#include<stdio.h>#define MAX 5char queue[MAX][30];int front, rear, temp;void init(){

front = rear = -1;}void insert(){

if (rear >= MAX-1){

printf("\nQueue overflow");return;

}temp = rear;rear = (rear + 1) % MAX;if (condition())

{rear = temp;printf("\nQueue overflow");

}else

{printf("\nEnter name to be inserted :\n");scanf("%s",queue[rear]);

}}void delete(){

if (condition())printf("\nError : Underflow");

else{

front = (front + 1) % MAX;printf("\nDeleted name from the CQ is %s",queue[front]);

}}int condition(){

if (rear == front){

front = rear = -1;return 1;

}else

return 0;}void display(){

int i;printf("\nThe queue content is :\n");if (front > rear)

{for (i = front + 1; i < MAX; i++)

printf("%s\t",queue[i]);for (i = 0; i <= rear; i++)

printf("%s\t",queue[i]);}

Expt No : 5 CIRCULAR QUEUE 20

Page 21: D.S

elsefor (i = front + 1; i <= rear; i++)

printf("%s\t",queue[i]);printf("\n");

}void main(){

int item, choice;init();while(1){

printf("\nMENU\n1. Insert\n2. Delete\n3. Display\n4. Exit\n");printf("\nYour choice = ?");scanf("%d",&choice);switch(choice){

case 1:insert();break;

case 2:delete();break;

case 3:if (condition())

printf("\nNo elements in the list");else

display();break;

case 4:exit(0);

default:printf("Invalid Choice");

}}

}

Expt No : 5 CIRCULAR QUEUE 21

Page 22: D.S

PROBLEM : Using Dynamic variables and pointers, write a C program to construct a Singly Linked List consisting of the following informations in each node : Job_id(Integers), Job_name(Character String), Job_desc(Character string). The operations to be supported are :1. LINSERT – Inserting in the front of the list.2. LDELETE – Deleting a node based on Job_id.3. LSEARCH – Searching a node based on Job_id.4. LDISPLAY – Displaying all the nodes in the list.

DEFINITION : LINKED LISTSLinked list is a common data structure often used to store similar data in memory. While the elements of an array occupy contiguous memory locations, those of a linked list are not constrained to be stored in adjacent locations. The individual elements are stored somewhere in the memory, rather like a family dispersed, but still bound together. The order of the elements is maintained by explicit links between them. For instance, this is how the marks obtained by different students can be stored in list: Data next

Null

Observe that the linked list is a collection of elements called nodes each of which contains two items of information:1. An element of the list2. Link i.e. a pointer that indicates the location of the node containing the successor of this list element.In the figure, arrows represent the links. The data part of each node consists of marks and the next part contains the pointer to the next node. The null indicates the last node.

So, a linked list is an ordered collection of structures by logical links that are stored as a part of data in the structure itself. The link is in the form of a pointer to another structure of same type. Node struct node

{ int item; struct node *next;

}; item nextThe first member is an integer item and the second is a pointer to the next node in the list as shown in figure. Remember, the item is an integer in this case and could be any complex data type.

Such structures that contain a member field that points to the same structure type are called self-referential structures.A node may be represented in general as follows: strut tag-name{

type member 1; type member 2; . . . . . . . . . . . . . . . . . . . . . . . . . . struct tag-name *next;

};The structure may contain more than one item with different data types. However one of the items must be a pointer of the tag-name.

null

Expt No : 6 SINGLY LINKED LIST 22

70 65 45 62

Page 23: D.S

member 1 member 2 member n next

Page 24: D.S

ALGORITHM : SINGLY LINKED LISTS

Procedure INSERT (id,name,desc,START) : Given Jobid, Jobname, Jobdesc and START, a pointer to the first element of a linear linked list whose node

typically contains Job_id, Job_name, Job_desc and NEXT fields.

Expt No : 6 SINGLY LINKED LIST 23

Page 25: D.S

\5eThis procedure insert id, name, desc. Here TEMP is a temporary pointer variable. It is required that id, name & desc precede the node whose address is given by START. AVAIL returns the address of the newly created free node.

STEP 1 : [Obtain the address of next free node or a new node]TEMP AVAIL

STEP 2 : [Initialize fields of new node TEMP and its link to the list]Job_id(TEMP) idJob_name(TEMP) nameJob_desc(TEMP) descNEXT(TEMP) START

STEP 3 : [The new node TEMP becomes the first node]START TEMPReturn

Procedure DELETE(START) : START, a pointer to the first element of a linear linked list whose node typically contains Job_id, Job_name, Job_desc & NEXT fields. This procedure deletes an element which is at the first position in the list. Here TEMP is a temporary variable.

STEP 1 : [Check for Underflow condition]If (START == NULL)Then Write (‘Error : Underflow’)

ReturnSTEP 2 : [Initialize the node TEMP to be deleted from the list]

TEMP STARTSTEP 3 : [Move the START pointer to the next node]

START NEXT(TEMP)STEP 4 : [Display the values of node TEMP and free it.]

Write (Job_id(TEMP), Job_name(TEMP), Job_desc(TEMP))Free (TEMP)Return

Page 26: D.S

#include<stdio.h>#define getnode() ( (list *)malloc(sizeof(list)) )struct link {

int Job_id;char Job_name[30], Job_desc[30];struct link *next;

};typedef struct link list;

list *start = NULL;void Delete(){ int item,jobid,count=1; list *temp, *prev; if (start == NULL)

printf("\nError : Underflow"); else {

printf("\nEnter Job-id of the node to be deleted : ");scanf("%d",&jobid);temp = prev = start;while (temp->Job_id != jobid){

prev = temp; temp = temp->next; if (temp == NULL) { printf("\nUnable to delete.");

printf("\nItem or Job-Id : %d not found in the list",jobid); return; } count++;

}if (count == 1) if (temp->next == NULL)

start = NULL;else

start = start->next;else

prev->next = temp->next;printf("\nDeleted item is :");printf("\nJob Id : %d",temp->Job_id);printf("\nJob Name : %s",temp->Job_name);printf("\nJob Desc : %s",temp->Job_desc);free(temp);

}}void Display(){

list *temp;if (start == NULL)

printf("\nNo elements in the list");else{temp = start;printf("\nAll the node elements in the list is as follows :\n");while (temp != NULL)

{printf("\nJob Id : %d",temp->Job_id);

Expt No : 6 SINGLY LINKED LIST 24

Page 27: D.S

printf("\nJob Name : %s",temp->Job_name);printf("\nJob Desc : %s\n",temp->Job_desc);temp = temp->next;

}}

}void Insert(){

list *temp;temp = getnode();

printf("\nEnter an item for the Job_id field : ");scanf("%d",&temp->Job_id);printf("\nEnter an item for the Job_name field : ");scanf("%s",temp->Job_name);printf("\nEnter an item for the Job_desc field : ");scanf("%s",temp->Job_desc);

temp->next = start;

start = temp;}void Search(){

int item,jobid,count=1;list *temp, *prev;if (start == NULL)

printf("\nError : Underflow");else{ printf("\nEnter Job-id of the node to be find in the list : "); scanf("%d",&jobid); temp = prev = start; while (temp->Job_id != jobid) { prev = temp; temp = temp->next; if (temp == NULL) {

printf("\nSearch Failure");printf("\nItem or Job-Id : %d not found in the list",jobid);return;

} count++; } printf("\nItem found at node=%d is as follows :",count); printf("\nJob Id : %d",temp->Job_id); printf("\nJob Name : %s",temp->Job_name); printf("\nJob Desc : %s",temp->Job_desc);

}}void main(){int ch,item;clrscr();do{ printf("\nMENU\n1. Insert\n2. Delete\n3. Display\n4. Search\n5. Exit\n"); printf("\nYour Choice = ?");

Expt No : 6 SINGLY LINKED LIST 25

Page 28: D.S

scanf("%d",&ch); switch(ch)

{case 1:

Insert();Display();break;

case 2: Delete();break;

case 3: Display();break;

case 4: Search();break;

case 5: exit(0);

default: printf("\nInvalid Choice Selection. Try Again");}

}while (ch != 5);getch();}

Expt No : 6 SINGLY LINKED LIST 26

Page 29: D.S

PROBLEM : A deque is a list in which items can be added or deleted from either end of the list. Implement the following C functions to simulate the working of such a deque of integers, using Pointers and Dynamic variables.1.RemLeft 2.RemRight 3.InsertLeft 4.InsertRight5.Display

DEFINITION : A deque is a list in which items can be added or deleted from either end of the list.

ALGORITHM : DEQUEProcedure Linsert(data) : Insert item at front node of list. AVAIL is the newly created free node.STEP 1 : [Create new node] temp AVAILSTEP 2 : [Insert item into the newnode temp]

Info(temp) dataSTEP 3 : [Next pointer of newnode points to start node]

Next(temp) startSTEP 4 : [Now newnode temp is start node]

Start temp

Procedure Ldelete() : Return the item to be deleted at front node if present, otherwise return 0.STEP 1 : [Check for Underflow condition]

If (start == NULL) return 0else goto STEP 2

STEP 2 : [Consider temp as start node]temp start

STEP 3 : [Move the start pointer and assign the info of temp to item]item info(temp)

STEP 4 : [Delete front node. Also return the item to be deleted]free(temp)return (item)

Procedure Rinsert(data) : Insert data at the end of the node in the list.STEP 1 : [Create a newnode and insert data into it]

newnode AVAILinfo(newnode) datanext(newnode) NULL

STEP 2 : [Consider temp as start node]temp start

STEP 3 : [Link newnode by checking whether the list contains nodes or not]if (temp == NULL)

start newnodeelse

while (next(temp) != NULL)temp temp->next;

temp->next newnode;return

#include<stdio.h>

Expt No : 7 DEQUE 27Expt No : 7 DEQUE 27

Page 30: D.S

#define getnode() ( (list *)malloc(sizeof(list)) )struct link {

int info; struct link *next;};

typedef struct link list;list *start = NULL;int LDelete(){

int item;list *temp;if (start == NULL)

return 0;else

{temp = start;start = start->next;item = temp->info;free(temp);return item;

}}void Display(){

list *temp;if (start == NULL)

printf("\nNo elements in the list");else

{temp = start;printf("\nElements in list is as follows:\nROOT-> ");while (temp != NULL)

{printf("%d -> ",temp->info);temp = temp->next;

}printf("NULL");

}}void LInsert(int data){

list *temp;temp = getnode();temp->info = data;temp->next = start;start = temp;

}void RInsert(int data){

list *newnode,*temp;newnode = getnode();newnode->info = data;newnode->next = NULL;temp = start;if (temp == NULL)

start = newnode;else

{while (temp->next != NULL)

Expt No : 7 DEQUE 28

Page 31: D.S

temp = temp->next;temp->next = newnode;

}}int RDelete(){

int item;list *temp,*prev;if (start == NULL)

return 0;else

{temp = start;if (temp->next == NULL)

{item = temp->info;free(temp);start = NULL;return item;

}while (temp->next != NULL)

{prev = temp;temp = temp->next;

}prev->next = NULL;item = temp->info;free(temp);return item;

}}void main(){int ch,item;clrscr();while(1){ printf("\nSELECTION MENU\n1. Insert Left\n2. Delete Left\n3. Insert Right");

printf("\n4. Delete Right\n5. Display\n6. Exit");printf("\nYour Choice = ?");scanf("%d",&ch);switch(ch){

case 1:printf("\nEnter an item for the info field : ");scanf("%d",&item);LInsert(item);Display();break;

case 2:if ( (item=LDelete()) )printf("\nDeleted item is %d",item);

elseprintf("\nError : Underflow");

break;

case 3:printf("\nEnter an item for the info field : ");scanf("%d",&item);RInsert(item);Display();

Expt No : 7 DEQUE 29Expt No : 7 DEQUE 30

Page 32: D.S

break;

case 4:if ((item=RDelete()))printf("\nDeleted item is %d",item);

elseprintf("\nError : Underflow");

break;

case 5:Display();break;

case 6:exit(0);

default: printf("\nInvalid Choice Selection. Try Again");

} /* End of Switch */} /* End of While */getch();} /* End of Main Program */

Page 33: D.S

PROBLEM : Write a C program using Dynamic variables and Pointers, to perform the following operations :(a). Construct two Ordered (Ascending) Singly Linked Lists.(b). Combine these two ordered lists into a single ordered lists.

ALGORITHM : SORT & MERGE TWO LINEAR LINKED LISTS

STEP1 : Create first list and display itSTEP2 : Create second list and display itSTEP3 : Sort first list and display itSTEP4 : Sort second list and display itSTEP5 : Merge first and second sorted lists and store it in a third listSTEP6 : Display the resultant or third list.

Expt No : 8 SORT & MERGE 2 LINKED LISTS 31

Page 34: D.S

#include<stdio.h>#define getnode() ((list *)malloc(sizeof(list)))struct node {

int info;struct node *next;

};typedef struct node list;list *last = NULL;/* FUNCTION TO CREATE A LINKED LIST */void create(list **start){

list *temp,*prev;int item;printf("\nEnter an item or -999 : ");scanf("%d",&item);prev = *start;while (item != -999){

temp = getnode();temp->info = item;temp->next = NULL;if (*start == NULL)

*start = temp;else

prev->next = temp;prev = temp;printf("\nEnter an item or -999 to stop : ");scanf("%d",&item);

}}/* FUNCTION TO SORT THE LINKED LIST */void sort(list **s){

list *t1,*t2;int x;for (t1=*s; t1 != NULL; t1=t1->next){

for (t2=t1->next; t2 != NULL; t2=t2->next)if (t1->info > t2->info)

{x = t1->info;t1->info = t2->info;t2->info = x;

}}

}/* FUNCTION TO DISPLAY THE CONTENT OF A LINKED LIST */void display(list **s){

list *t;t = *s;if (t == NULL)

printf("\nList is Empty");else

{printf("\nROOT->");while (t != NULL)

{printf("%d->",t->info);

Expt No : 8 SORT & MERGE 2 LINKED LISTS 32

Page 35: D.S

t = t->next;}

printf("NULL");}

}/* FUNCTION TO ADD A NODE TO MERGED LIST */void addtolist(list **s, int x){

list *new;new = getnode();new->info = x;new->next = NULL;if (*s == NULL)

*s = new;else

last->next = new;last = new;

}/* FUNCTION TO MERGE TWO LINKED LISTS */list *merge(list *p, list *q){

list *start,*t1,*t2;int a,b;start = NULL;t1 = p;t2 = q;while (p != NULL && q != NULL)

{a = p->info;b = q->info;if (a == b)

{addtolist(&start,a);p = p->next;addtolist(&start,b);q = q->next;

}else if (a < b)

{addtolist(&start,a);p = p->next;

}else

{addtolist(&start,b);q = q->next;

}}if (p != NULL)

while (p != NULL){

addtolist(&start, p->info);p = p->next;

}if (q != NULL)

while (q != NULL){

addtolist(&start,q->info);q = q->next;

Expt No : 8 SORT & MERGE 2 LINKED LISTS 33

Page 36: D.S

}p = t1; /* SAVE THE STARTING ADDRESSES OF P AND Q */q = t2;return start;

}void main()/* MAIN PROGRAM */{

int choice;list *start1, *start2, *start;start1 = start2 = start = NULL;clrscr();printf("Enter the elements of first list :\n");create(&start1); /* CREATE FIRST LIST */display(&start1);printf("\nEnter the elements of second list :\n");create(&start2); /* CREATE SECOND LIST */display(&start2);sort(&start1); /* SORT THE FIRST LIST */sort(&start2); /* SORT THE SECOND LIST */

while (1){

printf("\nMENU\n1. DISPLAY SORT1\n2. DISPLAY SORT LIST2\n");printf("3. MERGE LIST1 AND LIST2\n4. DISPLAY MERGED LIST\n5. EXIT");printf("\nEnter your choice : ");scanf("%d",&choice);switch (choice){

case 1:printf("\nThe first sorted list is :\n");display(&start1);break;

case 2:printf("\nThe second sorted list is :\n");display(&start2);break;

case 3:start = merge(start1, start2);break;

case 4:printf("The merged sorted list is :\n");display(&start);break;

case 5:exit(0);

default:printf("\nInvalid choice");

}}}

Expt No : 8 SORT & MERGE 2 LINKED LISTS 9Expt No : 8 SORT & MERGE 2 LINKED LISTS 34

Page 37: D.S

PROBLEM : Using the Circular Linked List Data Structure, Write a C program to Add two long positive integers. The Circular Lists can have Header nodes and the numbers are to be inputted in a normal way. Each node in the list contains a single digit of the number.

DEFINITION : The Circular Linked Lists have no beginning and no end. The last item or node points back to the first item or node. It can be created in 2 ways using : (a) Header node (b)Start & last pointers

ALGORITHM : Add two long positive integers using Circular Linked List

STEP1 : Accept first number one digit at a time, assign it to s1 & display itSTEP2 : Accept second number one digit at a time,assign it to s2 & display it STEP3 : p<-s1,q<-s2. To add digits of 2 given numbers follow the procedure : If both numbers have same number of digits Then add the two digits, Find num & cr (carry) and num is stored in the node. Now increment the pointers start,p & q. If digit in first number is bigger than the digit in second number Then digit in first number is added to cr(carry) & store it in node. Now increment the pointers start & p, Also cr<-0 If digit in second number is bigger than the digit in first number Then digit in second number is added to cr(carry) & store it in node. Now increment the pointers start & q, Also cr<-0STEP4 : Add till both the numbers have same digitSTEP5 : If there is any cr (carry) then store it in a node. Now increment the pointer start only.STEP6 : Return the resultant node start & Display the result in main program

Expt No : 9 CIRCULAR LINKED LIST 35

Page 38: D.S

#include<stdio.h>/* MACRO FUNCTION TO ALLOCATE MEMORY FOR NODE DYNAMICALLY */#define getnode() ( (clist *) malloc(sizeof(clist)) )struct node {

int info;struct node *next;

};typedef struct node clist;clist *last = NULL;/* FUNCTION TO CREATE A CIRCULAR LINKED LIST */clist *ccreate(clist *start){

clist *temp, *head; /* head IS A HEADER NODE WHICH CONTAINS 0 DATA */int item;start = NULL;head = getnode();head->info = 0;head->next = head;printf("\nEnter a digit or -999 to stop : ");scanf("%d",&item);while (item != -999)

{temp = getnode();temp->info = item;if (start == NULL)

{temp->next = head;head->next = temp;start = temp;

}else

{temp->next = head;start->next = temp;start = temp;

}printf("\nEnter a digit or -999 to stop : ");scanf("%d",&item);

}return head;

}/* FUNCTION TO INSERT THE ADDED DIGIT TO THE FINAL LIST */void insert(clist **s, int x){

clist *t;t = getnode();t->info = x;t->next = (*s)->next;(*s)->next = t;

}/* FUNCTION TO ADD DIGITS OF GIVEN TWO NUMBERS */clist *add(clist *p, clist *q){

int cr=0, num=0, sum=0;clist *s, *x, *y;x = p;y = q;s = getnode();s->info = 0;

Expt No : 9 CIRCULAR LINKED LIST 36

Page 39: D.S

s->next = s;p = p->next;q = q->next;while ((p != x) || (q != y))

{ /* ADD TILL BOTH NUMBERS HAVE SAME DIGITS*/if ((p != x) && (q != y))

{sum = p->info + q->info + cr;num = sum % 10;cr = sum / 10;insert(&s, num);s = s->next;p = p->next;q = q->next;

}else if (p != x) /* IF FIRST NUMBER IS BIGGER THAN SECOND */

{insert(&s,(p->info + cr));cr = 0;s = s->next;p = p->next;

}else if (q != y) /* IF SECOND NUMBER IS BIGGER THAN FIRST */

{insert(&s,(q->info + cr));cr = 0;s = s->next;q = q->next;

}}if (cr == 1)

{insert(&s, cr);s = s->next;

}p = x; /* RESAVE THE STARTING ADDRESSES */q = y;return s->next;

}/* FUNCTION TO DISPLAY THE CONTENT OF A LIST */void cdisplay(clist **start){

clist *temp;int a[30], i=0;if (*start == NULL)

printf("\nList is empty");else

{temp = (*start)->next;do {

a[i++] = temp->info;temp = temp->next;

}while (temp != (*start));for (i=i-1; i>=0; i--)

printf("%d",a[i]);}

}/* MAIN PROGRAM */void main()

Expt No : 9 CIRCULAR LINKED LIST 9Expt No : 9 CIRCULAR LINKED LIST 37

Page 40: D.S

{clist *s, *s1, *s2, *s3;clrscr();printf("\nEnter the first number one digit at a time :\n");s1 = ccreate(s);printf("\nThe content of the first number is :\n");cdisplay(&s1);printf("\nEnter the second number one digit at a time :\n");s2 = ccreate(s);printf("\nThe content of the second number is :\n");cdisplay(&s2);s3 = add(s1, s2);printf("\nThe content of added number is : \n");cdisplay(&s3);getch();

}

Expt No : 9 CIRCULAR LINKED LIST 38

Page 41: D.S

PROBLEM : Write a C program using dynamic variables and pointers to support the following operations on Doubly Linked List of integers.(a) Create a Doubly Linked list by adding each node at the front(b) Insert a new node to the left of node whose key value is read as input(c) Delete all occurrences of a given key, if it is found, Otherwise display

appropriate message.(d) Display the contents of the list

DEFINITION : Doubly linked listDoubly linked list is a type of ordered list, in which each node consists of 2 pointers. One is to store the address of the next node. Another is to store the address of the previous node. Each node can have more than one data part, each of any type. Also called as 2-way list. (Rest is same as ordinary lists.)

The speciality of this list is that, the list can be traversed in both the directions i.e. both in forward as well as in backward directions. The concept of this type of list is used in trees. The hierarchial structure of the tree can be easily represented using these double linked lists.

The only disadvantage of these lists is that each node has 2 pointers, one for forward linking and another for backward linking. So additional memory is used for storing the backward linking pointer.

back data next back data next

back : pointer for backward traversing or to store address of previous node next : pointer for forward traversing or to store address of next nodedata : to store information of any number of data type.

Generally back pointer of first node and next pointer of last node is NULL to achieve 2-way list or Doubly linked list. But in case of Circular 2-way list the next pointer of last node points to the first node whereas back pointer of first node points to the last node.

ALGORITHM : DOUBLY LINKED LISTS

STEP 1 : Initialize pointers start & last as NULL.STEP 2 : create a doubly linked list by inserting each node at front.STEP 3 : Print the Menu.STEP 4 : If the choice is 1, then enter the element to be inserted to the left of the already existing node in a doubly linked list.STEP 5 : If the choice is 2, then delete all the occurances of the element to be deleted in the doubly linked list.STEP 6 : If the choice is 3, then display all the elements in doubly linked list.STEP 7 : If the choice is 4, then exit.STEP 8 : Repeat steps from 3 to 7 until the choice is 7.STEP 9 : Stop.

Expt No : 10 DOUBLY LINKED LIST 39

Page 42: D.S

#include<stdio.h>#define getnode() ( (dlist *)malloc(sizeof(dlist)) )struct node {

int info;struct node *back,*next;

};typedef struct node dlist;dlist *start = NULL, *last = NULL;/* FUNCTION TO CREATE A DOUBLY LINKED LIST BY ADDING EACH NODE AT THE FRONT */void create(){

dlist *newnode;int x;printf("\nEnter an item or -999 to terminate : ");scanf("%d",&x);while (x != -999)

{newnode = getnode();newnode->info = x;newnode->back = NULL;if (start == NULL)

{newnode->next = NULL;last = newnode;

}else

{newnode->next = start;newnode->next->back = newnode;

}start = newnode;printf("\nEnter an item or -999 to terminate : ");scanf("%d",&x);

}}/* FUNCTION TO DISPLAY THE CONTENT OF A LIST */void display(){

dlist *temp;if (start == NULL)

printf("\nList is empty");else

{temp = start;printf("\nThe Doubly linked list content is :\nFORWARD\nROOT ->");while (temp != NULL)

{printf(" %d ->",temp->info);temp = temp->next;

}printf("NULL");temp = last;printf("\n\nBACKWARD\nNULL");while (temp != NULL)

{printf(" <- %d",temp->info);temp = temp->back;

}printf(" <- ROOT");

Expt No : 10 DOUBLY LINKED LIST 40Expt No : 10 DOUBLY LINKED LIST 41

Page 43: D.S

}}void deleteall(int item){

dlist *temp,*prev;int i=0;if ((start == NULL) && (last == NULL))

{printf("\nUnderflow error");return;

}while (start->info == item)

{printf("\n%d occurance of node is deleted\n",++i);start = start->next;if (start == NULL)

{printf("\nList is ended");last = start;return;

}else

start->back = NULL;}

temp = prev = start;while (temp != NULL)

{prev = temp;temp = temp->next;if (temp == NULL)

{printf("\nList is ended");return;

}if (temp->info == item)

{prev->next = temp->next;if (temp->next != NULL)

temp->next->back = prev;else

last = prev;printf("\n%d occurance of node is deleted",++i);temp = prev;

}}

}void insert(int data){

dlist *temp,*newnode,*prev;if ((start == NULL) && (last == NULL))

{printf("\nNew node cannot be inserted to the left of the key node");return;

}newnode = getnode();newnode->info = data;temp = prev = start;if (temp->info == data)

{

Expt No : 10 DOUBLY LINKED LIST 42

Page 44: D.S

newnode->back = NULL;newnode->next = start;start->back = newnode;start = newnode;return;

}while (temp->info != data)

{prev = temp;temp = temp->next;if (temp == NULL)

{printf("\nYou cannot insert new node to left of the key node");return;

}}

newnode->next = prev->next;newnode->back = temp->back;prev->next = temp->back = newnode;

}/* MAIN PROGRAM */void main(){

int ch,data;clrscr();printf("Call to Create a Doubly linked list :\n");create();while (1){

printf("\nMENU\n1. Insert a new node to the left of the key node");printf("\n2. Delete all occurances of a given key\n3. Display\n4. Exit");printf("\nYour choice = ");scanf("%d",&ch);switch(ch){

case 1:printf("\nEnter the key value of the node to be inserted : ");scanf("%d",&data);insert(data);break;

case 2:printf("\nEnter the key value of the nodes to be deleted : ");scanf("%d",&data);deleteall(data);break;

case 3:display();break;

case 4:exit(0);

default: printf("\nInvalid choice. Try again");}

}}

Page 45: D.S

PROBLEM : Write a C program to implement an Ascending Priority Queue (assume integer data type) as a Binary Search Tree. The program should support the following operations : 1. PQInsert 2. PqminDelete 3. Traverse the tree using all the methods – InOrder, PreOrder & PostOrder – To display the elements in the tree.

DEFINITION : An ascending priority queue(apq) is a collection of items into which items can be inserted arbitrarily and from which only smallest item can be removed. If apq is an ascending priority queue, the operation pqinsert(apq,x) inserts element x into apq and pqmindelete(apq) removes the minimum element from apq and returns its value.

ALGORITHM : Ascending Priority Queue

STEP 1 : Initialize the root as zero.STEP 2 : Print the menu.STEP 3 : If the choice is 1, then insert the element into BST,if the key is

already present in the BST,then deletethe new key. If it's not found, then insert it in BST.

STEP 4 : If the choice is 2, then delete the min element in the BST.STEP 5 : If the choice is 3, then print the BST in Preorder ie., first print

the data in the root then go to left subtree and then right subtree.

STEP 6 : If the choice is 4, then display the BST in Inorder ie., first go to left subtree, then print the data in prev nodeand then go to right subtree.

STEP 7 : If the choice is 5, then Display the BST in Postorder ie., first go to left subtree and then go to the right subtree and then print the data in the node.

STEP 8 : Repeat the steps from 2-7 until the choice is not 6.STEP 9 : Stop.

Expt No : 11 ASCENDING PRIORITY QUEUE 43

Page 46: D.S

#include<stdio.h>struct node{

int data;struct node *left,*right;

};typedef struct node tree;void insert(tree **root,int num){

tree *new;if(*root==NULL){

new=(tree*)malloc(sizeof(tree));new->left=NULL;new->data=num;new->right=NULL;*root=new;

}else{

if(num<(*root)->data){

insert(&((*root)->left),num);}else{

insert(&((*root)->right),num);}

}}/* InOrder Traversal of Tree*/void inorder(tree *root){

if(root!=NULL){

inorder(root->left);printf("%d\t",root->data);inorder(root->right);

}}/*PreOrder Traversal of Tree */void preorder(tree *root){

if(root!=NULL){

printf("%d\t",root->data);preorder(root->left);preorder(root->right);

}}/* PostOrder Traversal of Tree */void postorder(tree *root){

if(root!=NULL){

postorder(root->left);postorder(root->right);printf("%d\t",root->data);

}

Expt No : 11 ASCENDING PRIORITY QUEUE 44

Page 47: D.S

}tree *findmin(tree *root){

tree *q=NULL,*par=NULL;if(root==NULL){

return(root);}else{

q=root;par=q;while(q->left!=NULL){

par=q;q=q->left;

}return(par);

}}void del(tree **root,tree *par){

tree *t;if((*root)->left!=NULL){ t=par->left; par->left=t->right; printf("%d",t->data); free(t);}else{

printf("%d",(*root)->data);t=*root;(*root)=t->right;free(t);

}}void main() /* MAIN PROGRAM */{

tree *root=NULL,*par=NULL;int num,choice;clrscr();while(1){

printf("\nMENU\n1.To insert\n2.To delete\n3.preorder\n4.inorder\n");printf("5.postorder\n6.exit\n");printf("Enter your choice : ");scanf("%d",&choice);switch(choice){

case 1:printf("\nEnter the element:");scanf("%d",&num);insert(&root,num);break;

case 2: if(root!=NULL){

par=findmin(root);del(&root,par);

Expt No : 11 ASCENDING PRIORITY QUEUE 45

Page 48: D.S

}else

printf("\nEmpty tree");break;

case 3:preorder(root);break;

case 4:inorder(root);break;

case 5:postorder(root);break;

case 6: exit();}

}}

Expt No : 11 ASCENDING PRIORITY QUEUE 46

Page 49: D.S

PROBLEM : Using pointers and dynamic variables, construct a binary search tree (BST) of integers. Write C functions to do the following : 1. Given a key, perform a search in the BST. If the key is found, then display “Key found”, Else insert the key in the BST.2. While constructing the BST, do not add any duplicates.3. Display the tree using any one of the traversal methods.

DEFINITION : A Binary Search Tree (BST) is a binary tree in which all elements in the left subtree of a node n are less than the contents of n, and all the elements in the right subtree of n are greater than or equal to the contents of n.ALGORITHM : BINARY SEARCH TREE (BST)STEP 1 : Initialize pointer root to zero.STEP 2 : Print the Menu.STEP 3 : If the choice is 1, then create the Bst by entering all the elements once.STEP 4 : If the choice is 2, then enter the element to be Inserted. If the same element is found, do not enter insert it. If not found, enter the key in BST.STEP 5 : If the choice is 3, then display in Preorder ie., print the data in root and then traverse thro'the left subtree and then thro' the right subtree.STEP 6 : If the choice is 4, then display in Inorder ie., first go to the left subtree, print the data in the prev node and then go to the right subtree.STEP 7 : If the choice is 5, then display in Postorder ie., first go to the left subtree and then go to right subtree and then print the data in the node.STEP 8 : Repeat the steps from 2-7 until the choice is 6.STEP 9 : Stop.

Expt No : 12 BINARY SEARCH TREE (BST) 47

Page 50: D.S

#include<stdio.h>struct node{

int data;struct node *left,*right;

};typedef struct node tree;tree *root;void insert(tree **root,int num){

tree *new;if(*root==NULL){

new=(tree*)malloc(sizeof(tree));new->left=NULL;new->data=num;new->right=NULL;*root=new;

}else{

if(num<(*root)->data)insert(&((*root)->left),num);

elseinsert(&((*root)->right),num);

}}void display(tree *root){

if(root!=NULL){

printf("%d \t",root->data);display(root->left);display(root->right);

}}void inorder(tree *root){

if(root!=NULL){

inorder(root->left);printf("%d\t",root->data);inorder(root->right);

}}void preorder(tree *root){

if(root!=NULL){

printf("%d\t",root->data);preorder(root->left);preorder(root->right);

}}void postorder(tree *root){

if(root!=NULL){

postorder(root->left);

Expt No : 12 BINARY SEARCH TREE (BST) 48

Page 51: D.S

postorder(root->right);printf("%d\t",root->data);

}}void search(tree *root,int key,int *flag){

tree *temp;temp=root;while(temp!=NULL){

if(temp->data==key){

*(flag)=1;printf("\nThe element was found and it is %d",temp->data);

}if(temp->data>key)

temp=temp->left;else

temp=temp->right;}

}void main() /* MAIN PROGRAM */{

int num,i,n,key,flag=0;i=0;clrscr();printf("Enter the number of elements you want to enter:");scanf("%d",&n);for(i=0;i<n;i++){

printf("\nEnter the element :");scanf("%d",&num);search(root,num,&flag);if(flag==1){ clrscr();

printf("The element already exists\n");printf("\nEnter another element:");i=i-1; flag=0;

}else

insert(&root,num);}printf("\nEnter the element to be searched:");scanf("%d",&key);search(root,key,&flag);if(flag==0){

printf("search not found!!Inserting key into tree\n");insert(&root,key);

}printf("\nThe contents of the list are:\n");display(root);printf("\nTraversal in in order :\n");inorder(root);printf("\nTraversal in preorder:\n");preorder(root);printf("\nTraversal in postorder:\n");postorder(root);

}

Expt No : 12 BINARY SEARCH TREE (BST) 49

Page 52: D.S

PROBLEM : Write a C program to evaluate a given expression (the operands of the expression may all be assumed of single character integer variables, the values of which may be obtained from the user seperately) using an Expression Tree.

DEFINITION : An ordered tree may be used to represent a general expression in much the same way that a binary tree may be used to represent a binary expression. Since a node may have any number of children, non-leaf nodes need not represent only binary operators but can represent operators with any number of operands. Such an ordered tree used to represent a general expr. is called an Expression Tree.

ALGORITHM : Expression Tree

STEP 1 : STARTSTEP 2 : Accept a postfix expression.STEP 3 : Store this expression in a string called str.STEP 4 : Process the given postfix expression using the function exptre.STEP 5 : Evaluation is done using the function eval.STEP 6 : Return the result and display the resultant value of the given postfix expression in main program.STEP 7 : STOP.

Expt No : 13 EXPRESSION TREE 50

Page 53: D.S

#include<stdio.h>#include<ctype.h>struct da{

char si; float va; struct da *l,*r; };

typedef struct da node;typedef struct da *nodeptr;char str[100];int pt;void setdata(nodeptr bt,float va,char si,nodeptr l,nodeptr r){ bt->va=va;bt->si=si;bt->l=l;bt->r=r; } void exptre(nodeptr *bt){ int i=pt--; nodeptr new=(nodeptr)malloc(sizeof(node)); if(i==-1) return; if(!isdigit(str[i])) { setdata(new,0,str[i],NULL,NULL);

*bt=new;exptre(&((*bt)->r));exptre(&((*bt)->l));

} else { setdata(new,str[i]-'0',' ',NULL,NULL);

*bt=new;return;

}}float eval(nodeptr bt){ if(bt->si!=' ') switch(bt->si)

{case '+':return(eval(bt->l)+eval(bt->r));case '*':return(eval(bt->l)*eval(bt->r));case '/':return(eval(bt->l)/eval(bt->r));case '-':return(eval(bt->l)-eval(bt->r));

} else return(bt->va);}void freeall(nodeptr bt){ if(bt==NULL) return; freeall(bt->l); freeall(bt->r); free(bt);}void main() /* MAIN PROGRAM */{ nodeptr bt=NULL; printf("Enter a postfix expression:"); scanf("%s",str); pt=strlen(str)-1; exptre(&bt); printf("\n%s = %.2f",str,eval(bt)); freeall(bt);}

Expt No : 13 EXPRESSION TREE 51

Page 54: D.S

PROBLEM : Write a C program to construct a Multi-linked representation of a Sparse Matrix. Assume that the matrix is of dimension M x N, where M is the number of rows & N is the number of columns. Using the Multi-Linked representation, write a function to add two Sparse Matrices.

#include<stdio.h>#define ma 30struct mod{

int row;int col;int val;struct mod *left,*up;

};typedef struct mod sparse;void create(sparse *mrow[],sparse *mcol[],int m,int n){

void init();void enter();int i,j,ele;init(mrow,mcol,m,n);for(i=1;i<=m;i++){ for(j=1;j<=n;j++)

{printf("\t");scanf("%d",&ele);/*printf("\t");*/if(ele)enter(mrow,mcol,i,j,ele);

}}

}void init(sparse *mrow[],sparse *mcol[],int m,int n){

int i;for(i=1;i<=m;i++){

mrow[i]=(sparse*)malloc(sizeof(sparse));mrow[i]->col=0;mrow[i]->left=mrow[i];

}for(i=1;i<=n;i++){

mcol[i]=(sparse*)malloc(sizeof(sparse));mcol[i]->row=0;mcol[i]->up=mcol[i];

}}void enter(sparse *mrow[],sparse *mcol[],int row,int col, int ele){

sparse *p,*q;int i;p=(sparse*)malloc(sizeof(sparse));p->row=row;p->col=col;p->val=ele;for(q=mrow[row];q->left->col!=0;q=q->left);p->left=q->left;q->left=p;

Expt No : 14 SPARSE MATRIX 52

Page 55: D.S

for(q=mcol[col];q->up->row!=0;q=q->up);p->up=q->up;q->up=p;

}void add(sparse *arow[],sparse *brow[],sparse *crow[],sparse *ccol[],int m,int n){

int i,j,sum;sparse *p,*q;init(crow,ccol,m,n);for(i=1;i<=m;i++){

p=arow[i]->left;q=brow[i]->left;while(p->col && q->col){

if(p->col<q->col){

j=p->col;sum=p->val;p=p->left;

}if(p->col>q->col){

j=q->col;sum=q->val;q=q->left;

}else{

sum=p->val+q->val;j=p->col;p=p->left;q=q->left;

}if(sum)

enter(crow,ccol,i,j,sum);}if(q->col)

p=q;for(;p->col!=0;p=p->left)

enter(crow,ccol,i,p->col,p->val);}

}void display(sparse *mrow[],int m){

int i;sparse *p=NULL;for(i=1;i<=m;i++){

printf("\t");for(p=mrow[i]->left;p->col!=0;p=p->left)

printf("%d\t%d\t%d\n",p->row,p->col,p->val);}

}void main(){

int m,n;sparse *arow[ma],*acol[ma],*brow[ma],*bcol[ma],*crow[ma];

Expt No : 14 SPARSE MATRIX 53

Page 56: D.S

sparse *ccol[ma];clrscr();printf("\nEnter the no of rows : ");scanf("%d",&m);printf("\nEnter the no of col : ");scanf("%d",&n);printf("\nEnter the elements of matrix a\n");create(arow,acol,m,n);printf("\nEnter the elements of matrix b\n");create(brow,bcol,m,n);clrscr();printf("\nthe elements of the matrix a are\n");display(arow,m);printf("The elements of the matrix b are\n");display(brow,m);add(arow,brow,crow,ccol,m,n);printf("\nthe elements of the resultant matrix are\n");display(crow,m);

}

Expt No : 14 SPARSE MATRIX 54

Page 57: D.S

PROBLEM : Write a C program to sort a list of n elements of integer type using Quick Sort algorithm.

DEFINITION : Quick sort method is also called partition exchange sort. In this method, at each step, the goal is to place a particular record in its final position within the table. In so doing, all records which precede this record have smaller keys, while all records that follow it have larged keys. This technique essentially divides the table into two sub-tables. The same process can then be applied to each of these sub-tables and repeated until all records are placed in their final positions.

ALGORITHM : Quick Sort

STEP 1 : Initialize an array.STEP 2 : Enter the no. of elements to be sorted.STEP 3 : Enter the elements to be sorted.STEP 4 : Sorting is done. Here the first element is placed in such a position

that all the elements to the left are less than it and all the elements to the right are greater than it. Let it be jth position.STEP 5 : Again continue the sorting process as in the above case, but here the elements are from 0 to j-1.STEP 6 : Again continue the sorting as in the above case, but here the Elements are from j+1 to n.STEP 7 : Print the sorted list.STEP 8 : Stop.

#include<stdio.h>int partition(int *a,int low,int high){

int i,j,temp,key;key=a[low];i=low+1;j=high;while(1){

while(i<high && key >=a[i])i++;

while(key < a[j]) j--;if(i<j){

temp=a[i];a[i]=a[j];a[j]=temp;

}else{

temp=a[low];a[low]=a[j];a[j]=temp;return j;

}}

Expt No : 15(a) QUICK SORT 56Expt No : 15(a) QUICK SORT 55

Page 58: D.S

}/* TO SORT THE LIST USING QUICKSORT TECHNIQUE */void quicksort(int *a,int low,int high){

int j;if(low<high){

j=partition(a,low,high);quicksort(a,low,j-1);quicksort(a,j+1,high);

}}/* MAIN PROGRAM */main(){

int i,n,a[20];clrscr();printf("Enter the limit\n");scanf("%d",&n);printf("\nEnter the elements\n");for(i=0;i<n;i++)

scanf("%d",&a[i]);quicksort(a,0,n-1);printf("\nSorted array is \n");for(i=0;i<n;i++)

printf("%d\n",a[i]);getch();

}

Page 59: D.S

PROBLEM : Write a C program to simulate the working of Towers of Hanoi problem for n disks. Print the number of moves taken by your program

DEFINITION : Tower of Hanoi

This problem consists of 3 pegs say A, B and C. There are n discs on peg A of different diameters and are placed on each other in such a way that always the smaller disc is placed above the larger disc. The 2 pegs B and C are empty. All the discs from peg A are transferred to peg C using peg B as temporary storage.The rules to be followed are :1. Smaller disc is on top of the larger disc at any time.2. A disc can be moved from one peg to another.

The initial set up of the problem is :

A B C

After transferring all the discs from A to C we get this set up :

A B C

ALGORITHM : TOWER OF HANOI PROBLEM

Procedure transfer(N,From,To,Temp)Transfer n disks from one pole to anotherN = no. of disksFrom = originTo = destinationTemp = temporary storage

Step 1 : Initialize number of discs.Step 2 : Move the top n-1 discs from L peg to C peg.Step 3 : Move the nth disk from L peg to R peg.Step 4 : Move the n-1 disks from C peg to R peg.Step 5 : Print the moves of the disks from each position.Step 6 : Print the total number of moves.Step 7 : Stop.

Expt No : 15(b) TOWER OF HANOI 57

Page 60: D.S

#include<stdio.h>#include<conio.h>int count=0;main(){ void transfer(int,char,char,char); int n; clrscr(); printf("\nWelcome to the TOWERS OF HANOI\n\n"); printf("\nHow many disks?==>"); scanf("%d",&n); transfer(n,'L','R','C'); printf("\ncount=%d",count); getch();}void transfer(int n,char from,char to,char temp)/* Transfer n disks from one pole to another n=no. of disks from=origin to=destination temp=temporary storage */{ if(n>0) { transfer(n-1,from,temp,to); /* move n-1 disks from origin to temporary */ printf("Move disk %d from %c to %c\n",n,from,to); count++; /* move nth disk from origin to destination */ transfer(n-1,temp,to,from); /* move n-1 disks from temporary to destination */ } return;}

Expt No : 15(b) TOWER OF HANOI 58