DS Lab Manual
DS Lab Manual
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 4
STACK AND QUEUE
Aim of Experiment: Implement Stack and Queue using arrays. Write a menu driven program
to perform following operations on stack a) Push b) Pop c) Display. Write a menu driven program
to perform following operations on Queue a) Insert b) Delete c) Display
OBJECTIVE: Objective of this experiment is to know concept of STACK and QUEUE. This assignment will
help the students to realize how the different operation on stack like push, pop, display can be implemented. This
assignment will help the student to realize the implementation difference between stack and queue. Also this will
clear the implementation concepts queue.
In computer science, a stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have
any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The
push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is
empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop
either reveals previously concealed items, or results in an empty list.
A stack is a restricted data structure, because only a small number of operations are performed on it. The nature
of the pop and push operations also mean that stack elements have a natural order. Elements are removed from
the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that
have been in the list the longest.
Stack Implementation
In most high level languages, a stack can be easily implemented either through an array or a linked list. What
identifies the data structure as a stack in either case is not the implementation but the interface: the user is only
allowed to pop or push items onto the array or linked list, with few other helper operations. The following will
demonstrate array implementation, using C.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
The array implementation aims to create an array where the first element (usually at the zero-offset) is the bottom.
That is, array[0] is the first element pushed onto the stack and the last element popped off. The program must
keep track of the size, or the length of the stack. The stack itself can therefore be effectively implemented as a
two-element structure in C:
typedef struct {
int size;
int items[STACKSIZE];
} STACK;
The push() operation is used both to initialize the stack, and to store values to it. It is responsible for inserting
(copying) the value into the ps->items[] array and for incrementing the element counter (ps->size). In a
responsible C implementation, it is also necessary to check whether the array is already full to prevent an
overrun.
The pop() operation is responsible for removing a value from the stack, and decrementing the value of ps-
>size. A responsible C implementation will also need to check that the array is not already empty.
Queue Theory: A queue is a particular kind of collection in which the entities in the collection are kept in
order and the principal (or only) operations on the collection are the addition of entities to the rear terminal
position and removal of entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO)
data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed.
This is equivalent to the requirement that whenever an element is added, all elements that were added before have
to be removed before the new element can be invoked. A queue is an example of a linear data structure.
Queues provide services in computer science, transport and operations research where various entities such as
data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs
the function of a buffer.
Queues are common in computer programs, where they are implemented as data structures coupled with access
routines, as an abstract data structure or in object-oriented languages as classes. Common implementations are
circular buffers and linked lists.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Representing a Queue
The defining attribute of a queue data structure is the fact that allows access to only the front and back of the
structure. Furthermore, elements can only be removed from the front and can only be added to the back. In this
way, an appropriate metaphor often used to represent queues is the idea of a checkout line (Ford/Topp p. 385).
Other examples of queues are people traveling up an escalator, machine parts on an assembly line, or cars in line
at a petrol station. The recurring theme is clear: queues are essentially the same as a queue you would get in a
shop waiting to pay.
In each of the cases, the customer or object at the front of the line was the first one to enter, while at the end of
the line is the last to have entered. Every time a customer finishes paying for their items (or a person steps off the
escalator, or the machine part is removed from the assembly line, etc.) that object leaves the queue from the front.
This represents the queue “dequeue” function. Every time another object or customer enters the line to wait, they
join the end of the line and represent the “enqueue” function. The queue “size” function would return the length
of the line, and the “empty” function would return true only if there was nothing in the line.
Queue implementation
Theoretically, one characteristic of a queue is that it does not have a specific capacity. Regardless of how many
elements are already contained, a new element can always be added. It can also be empty, at which point
removing an element will be impossible until a new element has been added again.
A practical implementation of a queue, e.g. with pointers, of course does have some capacity limit, that depends
on the concrete situation it is used in. For a data structure the executing computer will eventually run out of
memory, thus limiting the queue size. Queue overflow results from trying to add an element onto a full queue
and queue underflow happens when trying to remove an element from an empty queue.
CONCLUSION:
Dept. of E & TC
(2023-24)
SAE, KONDHWA
QUESTIONS STACK:
1) what is a data structure? Explain types of data structures with example?
2) Write Applications of Stack?
3) How to Convert Postfix Expression To Infix Using Stack?
4) What is a stack? Which type of data structure is stack?
QUESTIONS QUEUE:
1) Differentiate between linear queue &circular queue?
2) Give applications of queue?
3) What is a queue? Explain with example?
4) Write the empty and full conditions of queue using arrays?
References :
1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5
typedef struct stack
{
int top;
int data[size];
}s;
void push(s*,int);
int pop(s*);
void display(s*);
void main(void)
{
s st;
int choice,item,item_deleted;
clrscr();
st.top=-1;
while(1)
{
printf("\nEnter the choice");
printf("\n1.push\n2.pop\n3.display\n4.exit");
printf("\nchoice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter the item");
scanf("%d",&item);
push(&st,item);
break;
case 2:
item_deleted=pop(&st);
if(item_deleted!=-1)
{
printf("\n Item_deleted=%d",item_deleted);
}
break;
case 3:
display(&st);
break;
default:
exit(0);
}
}
}
void push(s *st,int item)
{
if(st->top==size-1)
{
Dept. of E & TC
(2023-24)
SAE, KONDHWA
/* OUTPUT */
2.pop
3.display
4.exit
choice:1
3.display
4.exit
choice:1
Dept. of E & TC
(2023-24)
SAE, KONDHWA
int q[10];
int r;
int f;
int main()
{
int item,item_deleted,choice;
r=-1;
f=0;
//clrscr();
while(1)
{
printf("\n\nenter your choice");
printf("\n1)insert\n2)Delete\n3)display\n4)quit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nenter the item");
scanf("%d",&item);
insert_rare(item);
break;
case 2:
item_deleted=delete_front();
if(item_deleted!=-1)
printf("\nitem deleted=%d",item_deleted);
break;
case 3:
display();
break;
default:
exit(0);
}
}
}
void insert_rare(int item)
{
if(r==queue_size-1)
{
printf("\nqueue is overflowed");
return -1:
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA
r++;
q[r]=item;
}
int delete_front()
{
int item_deleted;
if(f>r)
{
printf("\nqueue is underflowed");
return -1;
}
item_deleted=q[f];
f++;
if(f>r)
{
f=0;
r=-1;
}
return item_deleted;
}
void display()
{
int i;
if(f>r)
{
printf("\nqueue is empty");
return;
}
printf("\ncontnets of queue are:");
for(i=f;i<=r;i++)
{
printf("%d",q[1]);
}
}
OUTPUT
item deleted=5
1)insert
2)Delete
3)display
4)quit
1
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 5
Evaluate postfix expression (input will be postfix expression).
Aim of Experiment:
Objective :
This assignment will help the student to know how the postfix expression evaluation.
Theory:
The expression a + b*(c - d )+ e written in postfix form is abcd - * + e +. This looks rather cryptic. You can get
the idea most easily if you read it backwards as `` add e to (add (times (c - d) and b) to a)''. A few more examples
are shown in Table which may serve better than an elaborate explanation:
Algorithm:
Postfix 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.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
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.
In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The
algorithm for the evaluation of postfix ex. is as follows :
Input:
Output:
FAQs :
References :
4. “C programming “ Balguruswamy.
5. ‘Fundamentals of datastructures” sartaj sahani.
6. “Data structures “ Tananbom
Conclusion:
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Program:
/*** Program for evaluation of Postfix Expression ***/
#include<stdio.h>
#include<conio.h>
#include<ctype.h> /* for isdigit()function */
#include<math.h> /* for pow() function */
#define max 100
struct post
{
int stack[max];
int top;
}pf;
int evaluate(char *s);
void push(struct post *q,int val);
int pop(struct post *q);
void main()
{
int n1,n2,n3;
char expr[max];
int val,res;
clrscr();
printf("\n\nenter postfix expr\t");
gets(expr);
val=evaluate(expr);
printf("\nthe evaluation is \t%d",val);
getch();
}
int evaluate(char *s)
{
int res,val,n1,n2,n3;
struct post pf;
pf.top=-1;
while(*s!='\0')
{
if(isdigit(*s))
{
res=*s-'0'; /* '0'=ASCII 48, '9'=ASCII 57 */
push(&pf,res);
}
else
{
n1=pop(&pf);
n2=pop(&pf);
switch(*s)
{
case'+':n3=n2+n1;
break;
case'-':n3=n2-n1;
break;
case'*':n3=n2*n1 ;
break;
Dept. of E & TC
(2023-24)
SAE, KONDHWA
case'/':n3=n2/n1;
break;
case'$':n3=pow(n2,n1) ;
break;
}
push(&pf,n3);
}
s++;
}
res=pop(&pf);
return(res);
}
val=q->stack[q->top];
q->top--;
return(val);
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 6
SINGLY LINKED LIST
Aim of Experiment:
a. Insert (at front, at end, in the middle), b. Delete (at front, at end, in the middle),
Design a program for other variants of singly linked list that include use of a pointer to last node, header
node, circular linked list, and circular list with header node.
The basic singly-linked list is shown in Figure (a). Each element of the list refers to its successor and the last
element contains the null reference. One variable, labeled head in Figure (a), is used to keep track of the list.
The basic singly-linked list is inefficient in those cases when we wish to add elements to both ends of the list.
While it is easy to add elements at the head of the list, to add elements at the other end (the tail ) we need to locate
the last element. If the basic basic singly-linked list is used, the entire list needs to be traversed in order to find its
tail.
Figure (b) shows a way in which to make adding elements to the tail of a list more efficient. The solution uses
a second variable, tail , which refers to the last element of the list. Of course, this time efficiency comes at the
cost of the additional space used to store the variable tail.
The singly-linked list labeled (c) in Figure illustrates two common programming tricks. There is an extra
element at the head of the list called a sentinel . This element is never used to hold data and it is always present.
The principal advantage of using a sentinel is that it simplifies the programming of certain operations. For
example, since there is always a sentinel standing guard, we never need to modify the head variable. Of course,
the disadvantage of a sentinel such as that shown in (c) is that extra space is required, and the sentinel needs to be
created when the list is initialized.
The list (c) is also a circular list . Instead of using a null reference to demarcate the end of the list, the last
element of the list refers to the sentinel. The advantage of this programming trick is that insertion at the head of
the list, insertion at the tail of the list, and insertion at an arbitrary position of the list are all identical operations.
Of course, it is also possible to make a circular, singly-linked list that does not use a sentinel. Figure (d) shows
a variation in which a single variable is used to keep track of the list, but this time the variable, tail, refers to the
last element of the list. Since the list is circular in this case, the first element follows the last element of the list.
Therefore, it is relatively simple to insert both at the head and at the tail of this list. This variation minimizes the
storage required, at the expense of a little extra time for certain operations.
Figure illustrates how the empty list (i.e., the list containing no list elements) is represented for each of the
variations given in Figure . Notice that the sentinel is always present in list variant (c). On the other hand, in
the list variants which do not use a sentinel, the null reference is used to indicate the empty list.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
In the following sections, we will present the implementation details of a generic singly-linked list. We have
chosen to present variation (b)--the one which uses a head and a tail--since is supports append and prepend
operations efficiently.
Algorithm:
Getnode (new)
Info (new) =x
if list = null
list = new
else
begin
p=list
list = new
else
begin
while (next (p) <> null) and (x >= info (next (p))) do
p= next (p)
current = list
trail = null
begin
trail = current
then
else
freenode (current)
else print (“node with the given value doesn’t exist in the list” )
count=0
count = count +1
Dept. of E & TC
(2023-24)
SAE, KONDHWA
if (current = null)
call print(“ node with the given value doesn’t exist in the list”)
else
if (list = null)
else
CONCLUSION: Thus we have learnt how to create singly linked list and we implemented singly linked list .
References:
“C programming “ Balguruswamy.
‘Fundamentals of datastructures” sartaj sahani.
“Data structures “ Tananbom
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Program:
//Singly Linked List
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
# include<malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}*node;
node getnode();
node create(node first);
node insert_front(int item,node first) ;
node delete_front(node first);
node insert_rear(int item ,node first) ;
node delete_rear(node first);
void search(node first);
void display(node first);
int main()
{
int item, choice;
node first =NULL;
//clrscr();
while(1)
{
printf("\n\n1:create\n2:insert a node from front\n3:insert from rear
end\n4:delete from front\n5:delete from rear end\n6:search\n7:display\n8:exit");
printf("\n enter the choice") ;
scanf("%d",&choice);
switch(choice)
{
case 1 :
first=create(first);
break;
case 2 :
printf("\nenter the item to be inserted") ;
scanf("%d",&item);
first=insert_front(item ,first);
break;
case 3:
printf("\nenter the item to be inserted") ;
scanf("%d",&item);
first=insert_rear(item ,first);
break;
case 4:
first=delete_front(first) ;
break;
case 5:
first=delete_rear(first) ;
break;
Dept. of E & TC
(2023-24)
SAE, KONDHWA
case 6:
search(first) ;
break;
case 7:
display(first);
break;
default:
exit(0);
}
}
//getch();
return 0;
}
node getnode()
{
node temp;
temp=(node)malloc(1*sizeof(struct Node));
if(temp==NULL)
{
printf("\n out of memory");
}
return temp;
}
node create(node first)
{
node temp,current;
int i,n,item;
printf("\n enter the nos of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
temp=getnode();
temp->next=NULL;
printf("\nenter the item");
scanf("%d",&item);
temp->data=item;
if(i==0)
{
first=temp;
current=first;
}
else
{
temp->next=current;
current=temp;
}
}
return current;
}
node insert_front(int item,node first)
{
node temp;
temp=getnode();
temp->next=NULL;
Dept. of E & TC
(2023-24)
SAE, KONDHWA
temp->data=item;
if(first==NULL)
{
first=temp;
}
else
{
temp->next=first;
first=temp;
}
return first;
}
node insert_rear(int item, node first) \
{
node temp,current;
temp=getnode();
temp->next=NULL;
temp->data=item;
if(first==NULL)
{
first=temp;
}
else
{
current=first;
while(current->next!=NULL)
{
current=current->next;
}
current->next=temp;
}
return first;
}
node delete_front(node first)
{
node temp;
int item_deleted;
if(first==NULL)
{
printf("\n first is empty");
return first;
}
else
{
temp=first;
first=first->next;
item_deleted=temp->data;
printf("\n iteam deleted is%d",item_deleted);
temp->next=NULL;
free(temp);
temp=NULL;
return first;
}
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA
//================================\\
Output
1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice1
1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice7
element in list are: 30 20 10
1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice2
1:create
Dept. of E & TC
(2023-24)
SAE, KONDHWA
1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice7
element in list are: 25 30 20 10 35
enter the choice4
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 7
STACK AND QUEUE
Aim of Experiment: Implement Stack and Queue using linked list. Write a menu driven program
to perform following operations on stack a) Push b) Pop c) Display. Write a menu driven program to
perform following operations on Queue a) Insert b) Delete c) Display
OBJECTIVE: Objective of this experiment is to know concept of STACK and QUEUE. This assignment will
help the students to realize how the different operation on stack like push, pop, display can be implemented. This
assignment will help the student to realize the implementation difference between stack and queue. Also this will
clear the implementation concepts queue.
In computer science, a stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have
any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The
push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is
empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop
either reveals previously concealed items, or results in an empty list.
A stack is a restricted data structure, because only a small number of operations are performed on it. The nature
of the pop and push operations also mean that stack elements have a natural order. Elements are removed from
the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that
have been in the list the longest.
Stack Implementation
In most high level languages, a stack can be easily implemented either through an array or a linked list. What
identifies the data structure as a stack in either case is not the implementation but the interface: the user is only
allowed to pop or push items onto the array or linked list, with few other helper operations. The following will
demonstrate linked list implementation, using C.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
The linked-list implementation is equally simple and straightforward. In fact, a stack linked-list is much simpler
than most linked-list implementations: it requires that we implement a linked-list where only the head node or
element can be removed, or popped, and a node can only be inserted by becoming the new head node.
Unlike the array implementation, our structure typedef corresponds not to the entire stack structure, but to a single
node:
Such a node is identical to a typical linked-list node, at least to those that are implemented in C.
The push() operation both initializes an empty stack, and adds a new node to a non-empty one. It works by
receiving a data value to push onto the stack, along with a target stack, creating a new node by allocating memory
for it, and then inserting it into a linked list as the new head:
if (node == NULL){
fputs("Error: no space available for node\n", stderr);
abort();
} else { /* initialize node */
node->data = value;
node->next = empty(*head) ? NULL : *head; /* insert new head if any */
*head = node;
}
}
A pop() operation removes the head from the linked list, and assigns the pointer to the head to the previous
second node. It check whether the list is empty before popping from it:
Queue Theory: A queue is a particular kind of collection in which the entities in the collection are kept in
order and the principal (or only) operations on the collection are the addition of entities to the rear terminal
position and removal of entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO)
data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
This is equivalent to the requirement that whenever an element is added, all elements that were added before have
to be removed before the new element can be invoked. A queue is an example of a linear data structure.
Queues provide services in computer science, transport and operations research where various entities such as
data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs
the function of a buffer.
Queues are common in computer programs, where they are implemented as data structures coupled with access
routines, as an abstract data structure or in object-oriented languages as classes. Common implementations are
circular buffers and linked lists.
Representing a Queue
The defining attribute of a queue data structure is the fact that allows access to only the front and back of the
structure. Furthermore, elements can only be removed from the front and can only be added to the back. In this
way, an appropriate metaphor often used to represent queues is the idea of a checkout line (Ford/Topp p. 385).
Other examples of queues are people traveling up an escalator, machine parts on an assembly line, or cars in line
at a petrol station. The recurring theme is clear: queues are essentially the same as a queue you would get in a
shop waiting to pay.
In each of the cases, the customer or object at the front of the line was the first one to enter, while at the end of
the line is the last to have entered. Every time a customer finishes paying for their items (or a person steps off the
escalator, or the machine part is removed from the assembly line, etc.) that object leaves the queue from the front.
This represents the queue “dequeue” function. Every time another object or customer enters the line to wait, they
join the end of the line and represent the “enqueue” function. The queue “size” function would return the length
of the line, and the “empty” function would return true only if there was nothing in the line.
Queue implementation
Theoretically, one characteristic of a queue is that it does not have a specific capacity. Regardless of how many
elements are already contained, a new element can always be added. It can also be empty, at which point
removing an element will be impossible until a new element has been added again.
Dept. of E & TC
(2023-24)
SAE, KONDHWA
A practical implementation of a queue, e.g. with pointers, of course does have some capacity limit, that depends
on the concrete situation it is used in. For a data structure the executing computer will eventually run out of
memory, thus limiting the queue size. Queue overflow results from trying to add an element onto a full queue
and queue underflow happens when trying to remove an element from an empty queue.
CONCLUSION:
QUESTIONS STACK:
1) what is a data structure? Explain types of data structures with example?
2) Write Applications of Stack?
3) How to Convert Postfix Expression To Infix Using Stack?
4) What is a stack? Which type of data structure is stack?
QUESTIONS QUEUE:
1) Differentiate between linear queue &circular queue?
2) Give applications of queue?
3) What is a queue? Explain with example?
4) Write the empty and full conditions of queue using arrays?
References :
1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}*NODE;
NODE getnode(void);
NODE push(int,NODE);
NODE pop(NODE head);
NODE create(NODE first);
void display(NODE head);
int main()
{
int ch,item,x;
NODE temp,head=NULL;
//clrscr();
while(1)
{
printf("\n Enter the choice");
printf("\n 1:push\n2:pop\n3:display\n4:exit");
printf("\n choice =");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n enter to be pushed\n");
scanf("%d",&item);
head=push(item,head);
break;
case 2:
head=pop(head);
break;
case 3:
display(head);
break;
default:exit(0);
}
}
return 0;
}
NODE push(int item,NODE head)
{
NODE temp;
temp=getnode();
temp->data=item;
temp->next=NULL;
if(head==NULL)
Dept. of E & TC
(2023-24)
SAE, KONDHWA
head=temp;
else
{
temp->next=head;
head=temp;
}
display(head);
return head;
}
NODE pop(NODE head)
{
NODE temp;
int x;
if (head==NULL)
{
printf("\n stack is empty");
}
else
{
temp=head;
printf("element popped is: %d",temp->data);
head=head->next;
temp->next=NULL;
free(temp);
display(head);
}
return head;
}
void display(NODE head)
{
NODE temp;
if(head==NULL)
{
printf("\n stack is empty");
}
else
{
temp=head;
printf("\n the elements in stack are:");
while(temp!=NULL)
{
printf("\n %d",temp->data);
temp=temp->next;
}
}
}
NODE getnode()
{
NODE temp;
temp=(NODE)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\n memory not available");
exit(0);
Dept. of E & TC
(2023-24)
SAE, KONDHWA
}
return temp;
}
NODE create(NODE first)
{
NODE temp;
int i,n,item;
printf("\n please enter the no of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n please enter the data");
scanf("%d",&item);
temp=getnode();
temp->data=item;
temp->next=NULL;
if(first==NULL)
{
first=temp;
}
else
{
temp->next=first;
first=temp;
}
}return first;
}
/* OUTPUT */
enter to be pushed
10
enter to be pushed
Dept. of E & TC
(2023-24)
SAE, KONDHWA
20
enter to be pushed
20
Dept. of E & TC
(2023-24)
SAE, KONDHWA
/* ==================================================================
*Program Description : Program to implement Queue using Linked List
*Name :
*Class : SE(EnTC)
*Roll no :
*Date :
==================================================================*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
//structure declaration
typedef struct node
{
int data;
struct node *next;
} *QUEUE;
//function declaration
QUEUE getnode(void);
QUEUE insert_rare(int item,QUEUE first);
QUEUE delete_front(QUEUE first);
void display(QUEUE first);
//======================main function==================
int main()
{
int ch,item;
QUEUE temp,first=NULL;
//clrscr();
while(1)
{
printf("\n\n Enter the choice");
printf("\n1):Insert\n2):Delete\n3):Display\n4):Exit\n");
scanf("%d",&ch);
switch(ch)
{
//enter choice from the user
}/*end of switch*/
}/*end of do_while*/
Dept. of E & TC
(2023-24)
SAE, KONDHWA
return 0;
}/*end of main*/
}
return x;
}
//=====================end of program===================
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 8
TREES
Aim of Experiment: Binary search tree: Create, search, recursive traversals.
OBJECTIVE:
Theory: In computer science, a tree is a widely-used data structure that emulates a hierarchical tree structure
with a set of linked nodes. Mathematically, it is not a tree, but an arborescence an acyclic connected graph where
each node has zero or more children nodes and at most one parent node. Furthermore, the children of each node
have a specific order.
Terminology
A node is a structure which may contain a value, a condition, or represent a separate data structure (which could
be a tree of its own). Each node in a tree has zero or more child nodes, which are below it in the tree (by
convention, trees grow down, not up as they do in nature). A node that has a child is called the child's parent
node (or ancestor node, or superior). A node has at most one parent.
Nodes that do not have any children are called leaf nodes. They are also referred to as terminal nodes.
The height of a node is the length of the longest downward path to a leaf from that node. The height of the root
is the height of the tree. The depth of a node is the length of the path to its root (i.e., its root path). This is
commonly needed in the manipulation of the various self balancing trees, AVL Trees in particular.
Conventionally, the value -1 corresponds to a subtree with no nodes, whereas zero corresponds to a subtree with
one node.
The topmost node in a tree is called the root node. Being the topmost node, the root node will not have parents.
It is the node at which operations on the tree commonly begin (although some algorithms begin with the leaf
nodes and work up ending at the root). All other nodes can be reached from it by following edges or links. (In
Dept. of E & TC
(2023-24)
SAE, KONDHWA
the formal definition, each such path is also unique). In diagrams, it is typically drawn at the top. In some trees,
such as heaps, the root node has special properties. Every node in a tree can be seen as the root node of the subtree
rooted at that node.
An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf node.
A subtree of a tree T is a tree consisting of a node in T and all of its descendants in T. (This is different from the
formal definition of subtree used in graph theory.[1]) The subtree corresponding to the root node is the entire tree;
the subtree corresponding to any other node is called a proper subtree (in analogy to the term proper subset).
Tree representations
There are many different ways to represent trees; common representations represent the nodes as records allocated
on the heap (not to be confused with the heap data structure) with pointers to their children, their parents, or both,
or as items in an array, with relationships between them determined by their positions in the array (e.g., binary
heap).
Binary Tree:
A binary tree is a finite set of nodes which is either empty or consists of root and two disjoint binary trees
called the left sub-tree and right sub-tree.
Binary search tree is binary tree which have all the values less than the root will lie in left sub tree & having
values greater than the root lie in right sub tree.
In computer science a binary search tree (BST) is a node based binary tree data structure which has the
following properties:
The left sub-tree of a node contains only nodes with keys less than the node's key.
The right sub-tree of a node contains only nodes with keys greater than the node's key.
Both the left and right sub-trees must also be binary search trees
Traversal:
Traversal is a systematic way of retrieving information from tree in such a way that no node will be left
unvisited or no node will be visited twice or more.
1) Pre-order
2) Post-order
3) In-order
4) Depth first search
5) Breadth first
1) Pre-order: In this data on the root node will be printed first then we move on the left sub-tree and go on
printing the data till we reach to the leftmost node. Print the data at that node and then move to the right
sub-tree.
2) In-order : In this traversal first we go towards the leftmost node to print data on that node then traversing
left sub-tree then print root node then traverse right subtree.
3) Post-order: In post order traversal we follow the LRD principle i.e. move to the leftmost node check if
right sub-tree is there or not if not then print the leftmost node, if right sub tree is there move towards
rightmost node.
CONCLUSION:
References:
“C programming “ Balguruswamy.
‘Fundamentals of datastructures” sartaj sahani.
“Data structures “ Tananbom
Program:
Dept. of E & TC
(2023-24)
SAE, KONDHWA
/*==============================================================
* Program Description : Program for Tree
* Name :
* Class : SE(EnTC)
* Roll no :
* Date :
=============================================================*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
//structure declaration
case 1:
T=create(T);
break;
case 2:
printf("\n Please enter the key to be found");
scanf("%d",&key);
Dept. of E & TC
(2023-24)
SAE, KONDHWA
p=search(key,T);
if(p==NULL)
printf("\n Key not found");
else
printf("\n Key found");
break;
case 3:
printf("\n Please enter the data to"\
"be inserted");
scanf("%d",&data);
T=insert(data,T);
break;
case 4:
preorder(T);
break;
case 5:
inorder(T);
break;
case 6:
postorder(T);
break;
case 7:
exit(0);
} /*end of switch*/
}/*end of do_while*/
return 0;
} /*end of main*/
BST create(BST T)
{
int data,n ,i;
printf("\n Please enter the number of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Please enter the data");
scanf("%d",&data);
T=insert(data,T);
}
return T;
}
}
else
{
cur=cur->lchild;
}
}
if(data>prev->item)
{
prev->rchild=temp;
}
else
{
prev->lchild=temp;
}
return T;
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA
void preorder(BST T)
{
if(T!=NULL)
{
printf("%d\t",T->item);
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(BST T)
{
if(T!=NULL)
{
inorder(T->lchild);
printf("%d\t",T->item);
inorder(T->rchild);
}
}
void postorder(BST T)
{
if(T!=NULL)
{
postorder(T->lchild);
postorder(T->rchild);
printf("%d\t",T->item);
}
}
//========================end of program====================
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 9
Graphs
Aim of Experiment:
Theory: Graph:
In computer science, a graph is an abstract data structure that is meant to implement the graph concept from
mathematics
A graph data structure consists mainly of a finite (and possibly mutable) set of ordered pairs, called edges or arcs,
of certain entities called nodes or vertices. As in mathematics, an edge (x, y) is said to point or go from x to y.
The nodes may be part of the graph structure, or may be external entities represented by integer indices or
references.
Formal Definition: A graph G can be defined as a pair (V, E), where V is a set of vertices, and E is a set of
edges between the vertices.
G= (V, E)
Adjacency matrix:
In mathematics and computer science, an adjacency matrix (or one-hop connectivity matrix) is a means of
representing which vertices of a graph are adjacent to which other vertices. Another matrix representation for a
graph is the incidence matrix Specifically, the adjacency matrix of a finite graph G on n vertices is the n × n
matrix where the non-diagonal entry aij is the number of edges from vertex i to vertex j, and the diagonal entry
aii, depending on the convention, is either once or twice the number of edges (loops) from vertex i to itself.
Undirected graphs often use the former convention of counting loops twice, whereas directed graphs typically use
the later convention. There exists a unique adjacency matrix for each graph (up to permuting rows and columns),
and it is not the adjacency matrix of any other graph. In the special case of a finite simple graph, the adjacency
matrix is a (0, 1)-matrix m with zeros on its diagonal. If the graph is undirected, the adjacency matrix is symmetric.
Operations:
Dept. of E & TC
(2023-24)
SAE, KONDHWA
1) Create a graph.
Input:
1) Adjacency matrix.
Output:
Application:
1. Network Analysis.
2. Artificial Intelligence
3. Compiler writing
4. Computer Graphics
5. Finding shortest route
Conclusion:
Questions:
1. Explain adjacency matrix and adjacency list. Construct adjacency matrix and adjacency list for the
following graph.
12
A
B 1
17 7
15
F 2 E
19
10
C D 6
14
2. Explain what are BFS and DFS?
Dept. of E & TC
(2023-24)
SAE, KONDHWA
References:
1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom “
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Program:
//Graphs
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
int a[20][20],visited[20],rear=-1,front=0,queue[20];
void bfs(int,int);
void dfs(int,int);
void add(int);
int delet();
int outdegree(int vertex,int n)
{
int i,count=0;
for(i=0;i<n;i++)
{
if(a[vertex][i]==1)
count++;
}
return count;
}
int indegree(int vertex,int n)
{
int i,count=0;
for(i=0;i<n;i++)
{
if(a[i][vertex]==1)
count++;
}
return count;
}
int main()
{
int vertex,n,choice,i,j;
clrscr();
printf("enter the no of vertices=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("press 1 if %d has a node with %d else press 0=",i,j);
scanf("%d",&a[i][j]);
}
}
printf("the adjacency matrix is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("enter 1-bfs\
\n 2-dfs\
\n 3-indegree\
\n 4-outdegree\
\n 5-exit\n");
while(1)
{
Dept. of E & TC
(2023-24)
SAE, KONDHWA
printf("\nenter vertex=");
scanf("%d",&vertex);
printf("enter your choice=");
scanf("%d",&choice);
for(i=0;i<20;i++)
{ queue[i]=NULL;visited[i]=NULL;front=0;rear=-1; }
switch(choice)
{
case 1:
bfs(vertex,n);break;
case 2:
dfs(vertex,n);break;
case 3:
printf("indegree of %d vertex is %d\n",vertex,indegree(vertex,n));
break;
case 4:
printf("outdegree of %d vertex is %d\n",vertex,outdegree(vertex,n));
break;
case 5:
printf("your programme ends here!!!\n");
getch();
exit(0);
}
}
return 0;
}
void bfs(int vertex,int n)
{
int i;
visited[vertex]=1;
printf("%d\t",vertex);
for(i=0;i<n;i++)
{
if((a[vertex][i]!=0)&&(visited[i]==0))
{
add(i);
visited[i]=1;
}
}
vertex=delet();
if(vertex!=-9)
bfs( vertex, n);
}
void add(int no)
{
if(rear==19)
printf("quque is full!!!\n");
else
{
rear++;
queue[rear]=no;
}
}
int delet()
{
int k;
if(front>rear)
return(-9);
else
{
k=queue[front];
front++;
Dept. of E & TC
(2023-24)
SAE, KONDHWA
return(k);
}
}
void dfs(int vertex,int n)
{
int i;
visited[vertex]=1;
printf("%d\t",vertex);
for(i=0;i<n;i++)
{
if((a[vertex][i]==1)&&(visited[i]==0))
dfs(i,n) ;
}
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA
EXPERIMENT 10
Implement Dijkstra’s Algorithm.
Aim of Experiment:
Objective :
This assignment will help the student to know how the implementation of Dijkstra’s Algorithm.
Theory:
Dijkstra algorithm is also called single source shortest path algorithm. It is based on greedy technique. The
algorithm maintains a list visited[ ] of vertices, whose shortest distance from the source is already known.
If visited[1], equals 1, then the shortest distance of vertex i is already known. Initially, visited[i] is marked as,
for source vertex.
At each step, we mark visited[v] as 1. Vertex v is a vertex at shortest distance from the source vertex. At each
step of the algorithm, shortest distance of each vertex is stored in an array distance[ ].
Dijkstra’s Algorithm
1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from vertex i to vertex j.
If there is no edge between vertices i and j then C[i][j] is infinity.
for(i=0;i<n;i++)
visited[i]=0;
Dept. of E & TC
(2023-24)
SAE, KONDHWA
4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
5. for(i=1;i<n;i++)
– Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
– Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of distance. i.e. for
each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
Time Complexity
The program contains two nested loops each of which has a complexity of O(n). n is number of vertices. So the
complexity of algorithm is O(n2).
References :
1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom
Conclusion:
Dept. of E & TC
(2023-24)
SAE, KONDHWA
Program:
//C Program on Dijkstra Algorithm for Finding Minimum Distance of Vertices from a Given Source in a Graph
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
return 0;
}
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
Dept. of E & TC
(2023-24)