Expt No: 1 (A) Stack 1
Expt No: 1 (A) Stack 1
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.
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(b) STACK – Evaluate Postfix 4
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.
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 5
6
/* 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;
else
return 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 6
clrscr();
printf("Enter a postfix expression :\n");
scanf("%[^\n]s",postfix);
printf("The result of the given expression is: .3f\n",process());
}
Expt No : 2 STACK – Infix to Postfix 7
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.
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 8
7
/* 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;
else
if (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 9
/* 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 : 3 STACK – Infix to Prefix 10
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.
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 11
/* 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 12
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 : 4(a) QUEUE 13
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.
ALGORITHM : QUEUE
Procedure 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 -1
STEP 2: [Check for overflow condition]
if (R>=(MAX-1))
then write ('Error : Overflow')
Return
STEP 3: [Increment rear pointer]
R R+1
STEP 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']
Return
STEP 2: [Increment the front pointer]
F F+1
STEP 3: [Delete element]
Y Q[F]
Return Y
Expt No : 4(a) QUEUE 14
/* PROGRAM TO IMPLEMENT A LINEAR QUEUE USING ARRAY */
#include<stdio.h>
#include<stdlib.h>
#define MAX 5
int 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;
else
return 0;
}
int underflow()
{
if (front>=rear)
return 1;
else
return 0;
}
int empty()
{
if (front==rear)
return 1;
else
return 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]);
else
if (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 15
{
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(b) PRIORITY QUEUE 16
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 3 rd 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.
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
ExptNoNo: :4(b)
5 SINGLY
CIRCULAR
LINKED
QUEUE
LIST 19
9
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
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')
Return
STEP 2 : [Increment the front pointer]
F (F+1)%MAX
STEP 3 : [Delete element]
Write(Q[F])
Return
Expt No : 5 CIRCULAR QUEUE 20
#include<stdio.h>
#define MAX 5
char 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 21
else
for (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 : 6 SINGLY LINKED LIST 22
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.
Data next
70 65 45 62 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 list
2. 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.
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
member 1 member 2 member n next
Expt No : 6 SINGLY LINKED LIST 23
ALGORITHM : SINGLY LINKED LISTS
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 26
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);
ALGORITHM : DEQUE
Procedure Linsert(data) : Insert item at front node of list. AVAIL is the
newly created free node.
STEP 1 : [Create new node]
temp AVAIL
STEP 2 : [Insert item into the newnode temp]
Info(temp) data
STEP 3 : [Next pointer of newnode points to start node]
Next(temp) start
STEP 4 : [Now newnode temp is start node]
Start temp
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 AVAIL
info(newnode) data
next(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 newnode
else
while (next(temp) != NULL)
temp temp->next;
temp->next newnode;
return
Expt No : 7 DEQUE 28
#include<stdio.h>
#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
{
Expt No : 7 DEQUE 29
while (temp->next != NULL)
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);
else
printf("\nError : Underflow");
break;
case 4: if ((item=RDelete()))
printf("\nDeleted item is %d",item);
else
printf("\nError : Underflow");
break;
case 5:
Display();
break;
case 6: exit(0);
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 : 9 CIRCULAR LINKED LIST 35
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 it
STEP2 : 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<-0
STEP4 : Add till both the numbers have same digit
STEP5 : 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 36
#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 37
9
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 38
{
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 : 10 DOUBLY LINKED LIST 39
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
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.
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.
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);
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) 48
#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);
else
insert(&((*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) 49
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 : 13 EXPRESSION TREE 50
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.
STEP 1 :
START
STEP 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 51
#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 : 14 SPARSE MATRIX 52
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 30
struct 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 53
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 54
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 : 15(a) QUICK SORT 55
56
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.
#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;
}
}
}
/* 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();
}
Expt No : 15(b) TOWER OF HANOI 57
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
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.
A B C
A B C
Procedure transfer(N,From,To,Temp)
Transfer n disks from one pole to another
N = no. of disks
From = origin
To = destination
Temp = 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 58
#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;
}