0% found this document useful (0 votes)
11 views52 pages

Competitive Coding Lab CS426

Uploaded by

fk324415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

Competitive Coding Lab CS426

Uploaded by

fk324415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Department of Computer Science & Engineering

LAB MANUAL

Session 2024-2025

Subject Name : - Competitive Coding Lab

Subject Code : - CS426

Branch : - CSE

Year : - 4th

Semester : - 7th

INTEGRAL UNIVERSITY LUCKNOW


Dasauli, Kursi Road, PO Basha-226026

Dept of CSE CS426


VISION
To produce highly skilled personnel who are empowered enough to transform the society by their education, research and
innovations.

MISSION
 To offer diverse academic programs at undergraduate, postgraduate, and doctorate levels that are in line with the current
trends in Computer Science and Engineering.
 To provide the state of the art infrastructure for teaching, learning and research.
 To facilitate collaborations with other universities, industry and research labs.

PROGRAM EDUCATIONAL OBJECTIVES (PEOS)


B Tech: Computer Science & Engineering

To produce graduates who have strong foundation of knowledge and skills in the field of computer science
PEO1 and engineering.

PEO2
To produce graduates who are employable in industries/public sector/research organizations or work as an
entrepreneur.

PEO3
To produce graduates who can provide solutions to challenging problems in their profession by applying
computer engineering theory and practices.

PEO4
To produce graduates who can provide leadership and are effective in multidisciplinary environment.

Dept of CSE CS426


List of Lab Exercises

Week Experiment No. Name of the Experiments Page No.

Week 1 Objective-1 Insert element in a Single Dimension Array. 6


1.1 Delete element in a Single Dimension Array. 7
Week 2-3 Objective-2 Overview of Sorting 8
2.1 Implement Bubble, Selection, Insertion Sort. 10
2.2 Implement Quick, Heap Sort. 16
Week 4-5-6 Objective-3 Overview of Linked List. 17
3.1 Implement Single Linked List and Traverse. 19
3.2 Implement Doubly Linked List and Traverse. 23
3.3 Implement Circular Linked List and Traverse. 26
Week 7 Objective-4 Overview of Stack Using Array and Linked List. 29
4.1 Implement Stack using Array. 30
4.2 Implement Stack using Linked List.
Week 8-9 Objective-5 Overview of Queue Using Array and Linked List. 33
5.1 Implement Queue using Array. 34
5.2 Implement Queue using Linked List.
5.3 Implement Circular Queue using Array and Linked List. 36
Week 10 Objective-6 Overview of Tree. 40
6.1 Implement Tree and Tree Traversal Using: - 42
In-order, Pre-order, Post-order
Week 11 Objective-7 Overview of Graph. 45
7.1 Creation of Graph and Graph Traversal Like BFS. 46
7.2 Creation of Graph and Graph Traversal Like DFS. 49
Week 12 Objective-8 Overview pattern matching of a Substring. 52
8.1 Implement Insert, Delete and Pattern matching of a
substring Using Linked List.

Dept of CSE CS426


Requirements: - Operating System-Windows XP, Linux, Ubuntu
Software: - Turbo C

Reference Books:-
1. S.K.Srivastava “Data Structure Through C”
2. R.B.Patel “Data Structure and Algorithms”
3. Yogesh Sachdeva “Data Structure Using C”
4. A.K. Sharma “Data Structure Using C”
5. A.A. Puntambekar “Data Structure and Algorithms”

(Books are Available in Departmental and Central Library at University campus)

Dept. Of CSE 5 CS426


Week #1
Experiment No 1

OBJECTIVE

 Insert element in a Single Dimension Array.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array. 

#include<stdio.h>
void main()
{
int a[4],i,pos,data;
printf("Enter the number");
for(i=0;i<3;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the position");
scanf("%d",&pos);
printf("Enter the Data");
scanf("%d",&data);
for(i=2;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=data;
printf("The Final Array is\n");
for(i=0;i<4;i++)
{
printf("%d\t",a[i]);
}
}

Dept. Of CSE 6 CS426


Experiment No 2

OBJECTIVE

 Delete element in a Single Dimension Array.


After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array. 

#include<stdio.h>
void main()
{
int a[5],i,pos,data;
printf("Enter the number");
for(i=0;i<4;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the position");
scanf("%d",&pos);
for(i=pos;i<4;i++)
{
a[i]=a[i+1];
}
printf("The Final Array is\n");
for(i=0;i<3;i++)
{
printf("%d\t",a[i]);
}
}

Dept. Of CSE 7 CS426


Experiment No 3
Week #2 Overview of Sorting.

Sorting:-

Sorting is any process of arranging items according to a certain sequence or in different sets,
and therefore, it has two common, yet distinct meanings:
Ordering: arranging items of the same kind, class or nature, in some ordered sequence,
Categorizing: grouping and labeling items with similar properties together (by sorts).

Bubble Sort:-

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that works
by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items
and swapping them if they are in the wrong order. The pass through the list is repeated until
no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from
the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to
operate on elements, it is a comparison sort. Although the algorithm is simple, most of the
other sorting algorithms are more efficient for large lists.

Selection Sort:-

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O (n2)
time complexity, making it inefficient on large lists, and generally performs worse than the
similar insertion sort. Selection sort is noted for its simplicity, and it has performance
advantages over more complicated algorithms in certain situations, particularly where
auxiliary memory is limited.
The algorithm divides the input list into two parts: the sublist of items already sorted, which
is built up from left to right at the front (left) of the list, and the sublist of items remaining to
be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted
sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest,
depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost
unsorted element (putting it in sorted order), and moving the sublist boundaries one element
to the right.

Dept. Of CSE 8 CS426


Insertion Sort:-

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item
at a time. It is much less efficient on large lists than more advanced algorithms such as quick
sort, heap sort, or merge sort. However, insertion sort provides several advantages: Simple
implementation
Efficient for (quite) small data sets
Adaptive (i.e., efficient) for data sets that are already substantially sorted: the time
complexity is O (n + d), where d is the number of inversions.
More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as
selection sort or bubble sort; the best case (nearly sorted input) is O(n) stable; i.e., does not
change the relative order of elements with equal keys in-place; i.e., only requires a constant
amount O(1) of additional memory space; i.e., can sort a list as it receives it When humans
manually sort something (for example, a deck of playing cards), most use a method that is
similar to insertion sort.

Quick Sort:-

Quick sort, or partition-exchange sort, is a sorting algorithm developed by Tony Hoare that,
on average, makes O(nlogn) comparisons to sort n items. In the worst case, it makes O (n2)
comparisons, though this behavior is rare. Quick sort is often faster in practice than other
O(nlogn) algorithms. Additionally, quick sort sequential and localized memory references
work well with a cache. Quick sort is a comparison sort and, in efficient implementations, is
not a stable sort. Quick sort can be implemented with an in-place partitioning, so the entire
sort can be done with only O(logn) additional space used by the stack during the recursion.

Merge Sort:-

In computer science, merge sort (also commonly spelled merge sort) is an O (n log n)
comparison-based sorting algorithm. Most implementations produce a stable sort, which
means that the implementation preserves the input order of equal elements in the sorted
output. Merge sort is a divide and conquer algorithm that was invented by John von
Neumann in 1945.

Dept. Of CSE 9 CS426


Experiment No 4

OBJECTIVE

Implement Bubble Sort Using Array.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array. 

#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1])
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}

Dept. Of CSE 10 CS426


Experiment No 5

OBJECTIVE

Implement Selection Sort Using Array.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array. 

#include <stdio.h>
int main()
{
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}

Dept. Of CSE 11 CS426


Experiment No 6

OBJECTIVE

Implement Insertion Sort Using Array.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array. 

#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}
for (c = 1 ; c <= n - 1; c++)
{
d = c;
while ( d > 0 && array[d] < array[d-1])
{
t=array[d];
array[d]=array[d-1];
array[d-1]=t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++)
{
printf("%d\n", array[c]);
}
return 0;
}
Dept. Of CSE 12 CS426
Experiment No 7

OBJECTIVE

Implement Quick Sort Using Array.


After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array and Function. 

#include<stdio.h>
void quicksort(int [10],int,int);
int main()
{
int x[20],size,i;
clrscr();
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",x[i]);
return 0;
}
void quicksort(int x[10],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j)
Dept. Of CSE 13 CS426
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
}

}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
}
}

Dept. Of CSE 14 CS426


Experiment No 8

OBJECTIVE

Implement Heap Sort Using Array.


After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Single Dimension Array and Function. 

#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x = *y;
*y = temp;
}
void heapsort(int a[],int n)
{
int i,s,f;
for(i=1;i< n;++i)
{
s=i;
f=(s-1)/2;
while( a[f]< a[s])
{
swap(&a[f],&a[s]);
s=f;
if(s==0)
break;
f=(s-1)/2;
}
}
for(i=n-1;i>=1;--i)
{
swap(&a[0],&a[i]);
f=0;
s=1;
if(i==1)
break;
if(i>2)if(a[2]>a[1])s=2;
while( a[f]< a[s] )
Dept. Of CSE 15 CS426
{
swap(&a[f],&a[s]);
f=s;
s=2*f+1;
if(i>s+1 )if(a[s+1]>a[s])s=s+1;
if (s>=i)
break;
}
}
}
void main()
{
int a[100],n,i;
clrscr();
printf("\t\tHEAP SORT\n");
printf("\nEnter The Number Of Elements\t: ");
scanf("%d",&n);
printf("\nEnter Elements\n");
for(i=0;i< n;++i)
scanf("%d",&a[i]);
heapsort(a,n);
printf("\n\t\t\tSorted List\n");
for(i=0;i< n;++i)
printf("\t%d",a[i]);
getche();
}

Dept. Of CSE 16 CS426


Week #3
Overview of Linked List.

Linked List:-

A linked list is a data structure consisting of a group of nodes which together represent a
sequence. Under the simplest form, each node is composed of a data and a reference (in other
words, a link) to the next node in the sequence; more complex variants add additional links.
This structure allows for efficient insertion or removal of elements from any position in the
sequence.

A linked list whose nodes contain two fields: an integer value and a link to the next node.
The last node is linked to a terminator used to signify the end of the list.

Linked lists are among the simplest and most common data structures. They can be used to
implement several other common abstract data types, including lists (the abstract data type),
stack, queues, associative arrays, and S-expressions, though it is not uncommon to
implement the other data structures directly without using a list as the basis of
implementation.
The principal benefit of a linked list over a conventional array is that the list elements can
easily be inserted or removed without reallocation or reorganization of the entire structure
because the data items need not be stored contiguously in memory or on disk. Linked lists
allow insertion and removal of nodes at any point in the list, and can do so with a constant
number of operations if the link previous to the link being added or removed is maintained
during list traversal.
On the other hand, simple linked lists by themselves do not allow random access to the data,
or any form of efficient indexing. Thus, many basic operations— such as obtaining the last
node of the list (assuming that the last node is not maintained as separate node reference in
the list structure), or finding a node that contains a given datum, or locating the place where
a new node should be inserted— may require scanning most or all of the list elements. The
advantages and disadvantages of using linked lists are as follows:-

Advantages:

Linked lists are a dynamic data structure, allocating the needed memory when the
program is initiated.
Insertion and deletion node operations are easily implemented in a linked list.
Linear data structures such as stacks and queues are easily executed with a linked list.
They can reduce access time and may expand in real time without memory overhead.

Dept. Of CSE 17 CS426


Disadvantages:

 They have a tendency to waste memory due to pointers requiring extra storage space.
Nodes in a linked list must be read in order from the beginning as linked lists are
inherently sequential access.
 Nodes are stored in contiguously, greatly increasing the time required to access
individual elements within the list.
 Difficulties arise in linked lists when it comes to reverse traversing. Singly linked lists
are extremely difficult to navigate backwards, and while doubly linked lists are
somewhat easier to read, memory is wasted in allocating space for a back pointer. 

Dept. Of CSE 18 CS426


Experiment No 9

OBJECTIVE

Implement Single Linked List and Traverse.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Structure of Linked List and perform various operations.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int info;
struct node *link;
}
*start;
void main()
{
int ch,n,m,pos,i;
clrscr();
start=NULL;
while(1)
{
printf("\n 1. Create");
printf("\n 2. insertatbeg");
printf("\n 3. insertatmiddle");
printf("\n 4. Delete");
printf("\n 5. Display");
printf("\n 6. Exit");
printf("\n Enter the choice:-");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n how many nodes u want to insert:-");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the data:-");
scanf("%d",&m);
create(m);

Dept. Of CSE 19 CS426


}
break;
case 2:printf("enter the elements:-");
scanf("%d",&m);
addatbeg(m);
break;
case 3:printf("enter the elements:-");
scanf("%d",&m);
printf("Enter the position after inserted:-");
scanf("%d",&pos);
addafter(m,pos);
break;
case 4:if(start==NULL)
{
printf("List is Empty:-");
continue;
}
printf("Enter the elements for deletion:-");
scanf("%d",&m);
del(m);
break;
case 5:disp();
break;
case 6:exit(0);
break;
default:printf("wrong Choice");
}
}
getch();
}
create(int data)
{
struct node *q,*temp;
temp=malloc(sizeof(struct node));
temp->info=data;
temp->link=NULL;
if(start==NULL)
start=temp;
else
{
q=start;
while(q->link!=NULL)
q=q->link;
q->link=temp;

Dept. Of CSE 20 CS426


}
}
addafter(int data,int pos)
{
struct node *q,*temp;
int i;
q=start;
for(i=0;i<pos-1;i++)
{
q=q->link;
if(q==NULL)
{
printf("There are less elements:-");
return;
}
}
temp=malloc(sizeof(struct node));
temp->link=q->link;
temp->info=data;
q->link=temp;
}
addatbeg(int data)
{
struct node *q,*temp;
temp=malloc(sizeof(struct node));
temp->info=data;
temp->link=start;
start=temp;
}
del(int data)
{
struct node *temp,*q;
if(start->info==data)
{
temp=start;
start=start->link;
free(temp);
return;
}
q=start;
while(q->link->link!=NULL)
{
if(q->link->info==data)
{

Dept. Of CSE 21 CS426


temp=q->link;
q->link=temp->link;

free(temp);
return;
}
q=q->link;
}
if(q->link->info==data)
{
temp=q->link;
free(temp);
q->link=NULL;
return;
}
}
disp()
{
struct node *q;
if(start==NULL)
{
printf("List is Empty");
return;
}
q=start;
printf("List is:-\n");
while(q!=NULL)
{
printf("%d->",q->info);
q=q->link;
}
printf("NULL");
}

Double Linked List:-

In a doubly linked list, each node contains, besides the next-node link, a second link field
pointing to the previous node in the sequence. The two links may be called forward(s) and
backwards, or next and prev(previous).

A doubly linked list whose nodes contain three fields: an integer value, the link forward to
the next node, and the link backward to the previous node

Dept. Of CSE 22 CS426


A technique known as XOR-linking allows a doubly linked list to be implemented using a
single link field in each node. However, this technique requires the ability to do bit
operations on addresses, and therefore may not be available in some high-level languages.
In the last node of a list, the link field often contains a null reference, a special value used to
indicate the lack of further nodes. A less common convention is to make it point to the first
node of the list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is
said to be 'open' or 'linear'.

Experiment No 10

OBJECTIVE

Implement Doubly Linked List and Traverse.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Structure of Doubly Linked List and perform various
operations. 

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
struct Node *prev;
}node;
void insert(node *pointer, int data)
{
while(pointer->next!=NULL)
{
pointer = pointer -> next;
}
pointer->next = (node *)malloc(sizeof(node));
(pointer->next)->prev = pointer;
pointer = pointer->next;
pointer->data = data;
pointer->next = NULL;
}
int find(node *pointer, int key)
{

Dept. Of CSE 23 CS426


pointer = pointer -> next; //First node is dummy node.
while(pointer!=NULL)
{
if(pointer->data == key) //key is found.
{
return 1;
}
pointer = pointer -> next;//Search in the next node.
}
return 0;
}
void delete(node *pointer, int data)
{
while(pointer->next!=NULL && (pointer->next)->data != data)
{
pointer = pointer -> next;
}
if(pointer->next==NULL)
{
printf("Element %d is not present in the list\n",data);
return;
}
node *temp;
temp = pointer -> next;
pointer->next = temp->next;
temp->prev = pointer;
free(temp);
return;
}
void print(node *pointer)
{
if(pointer==NULL)
{
return;
}
printf("%d ",pointer->data);
print(pointer->next);
}
int main()
{
node *start,*temp;
start = (node *)malloc(sizeof(node));
temp = start;
temp -> next = NULL;

Dept. Of CSE 24 CS426


temp -> prev = NULL;
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Print\n");
printf("4. Find\n");
while(1)
{
int query;
scanf("%d",&query);
if(query==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(query==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
else if(query==3)
{
printf("The list is ");
print(start->next);
printf("\n");
}
else if(query==4)
{
int data;
scanf("%d",&data);
int status = find(start,data);
if(status)
{
printf("Element Found\n");
}
else
{
printf("Element Not Found\n");

}
}
}
}

Dept. Of CSE 25 CS426


Circular Linked List:-

A circular linked list, In the case of a circular doubly linked list, the only change that occurs
is that the end, or "tail", of the said list is linked back to the front, or "head", of the list and
vice versa.

Experiment No 11

OBJECTIVE

Implement Circular Linked List and Traverse.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to declare Circular Linked List and perform various operations.

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
void insert(node *pointer, int data)
{
node *start = pointer;
while(pointer->next!=start)
{
pointer = pointer -> next;
}
pointer->next = (node *)malloc(sizeof(node));
pointer = pointer->next;
pointer->data = data;
pointer->next = start;
}
int find(node *pointer, int key)
{
node *start = pointer;
pointer = pointer -> next;
while(pointer!=start)

Dept. Of CSE 26 CS426


{
if(pointer->data == key)
{
return 1;
}
pointer = pointer -> next;
}
return 0;
}
void delete(node *pointer, int data)
{
node *start = pointer;
while(pointer->next!=start && (pointer->next)->data != data)
{
pointer = pointer -> next;
}
if(pointer->next==start)
{
printf("Element %d is not present in the list\n",data);
return;
}
node *temp;
temp = pointer -> next;
pointer->next = temp->next;
free(temp);
return;
}
void print(node *start,node *pointer)
{
if(pointer==start)
{
return;
}
printf("%d ",pointer->data);
print(start,pointer->next);
}
int main()
{
node *start,*temp;
start = (node *)malloc(sizeof(node));
temp = start;
temp -> next = start;
printf("1. Insert\n");
printf("2. Delete\n");

Dept. Of CSE 27 CS426


printf("3. Print\n");
printf("4. Find\n");
while(1)
{
int query;
scanf("%d",&query);
if(query==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(query==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
else if(query==3)
{
printf("The list is ");
print(start,start->next);
printf("\n");
}
else if(query==4)
{
int data;
scanf("%d",&data);
int status = find(start,data);
if(status)
{
printf("Element Found\n");
}
else
{
printf("Element Not Found\n");

}
}
}
}

Dept. Of CSE 28 CS426


Week #4
Overview of Stack Using Array and Linked List

Stack:-

A stack is a particular kind of abstract data type or collection in which the principal (or only)
operations on the collection are the addition of an entity to the collection, known as push and
removal of an entity, known as pop. The relation between the push and pop operations is
such that the stack is a Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the
last element added to the structure must be the first one to be removed. This is equivalent to
the requirement that, considered as a linear data structure, or more abstractly a sequential
collection, the push and pop operations occur only at one end of the structure, referred to as
the top of the stack. Often a peek or top operation is also implemented, returning the value of
the top element without removing it.

A stack may be implemented to have a bounded capacity. If the stack is full and does not
contain enough space to accept an entity to be pushed, the stack is then considered to be in
an overflow state. The pop operation removes an item from the top of the stack. A pop either
reveals previously concealed items or results in an empty stack, but, if the stack is empty, it
goes into underflow state, which means no items are present in stack to be removed.
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 those that have been on the stack the
longest.

Dept. Of CSE 29 CS426


Experiment No 12

OBJECTIVE

Implement Stack using Array.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to perform Overflow, Underflow and Traverse Stack Elements.
 Students perform Stack using Linked List.

#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 5
int stack[MAX_SIZE];
void push();
int pop();
void traverse();
int is_empty();
int top_element();
int top = -1;
main()
{
int element, choice;
while(1)
{
printf("Stack Operations.\n");
printf("1. Insert into stack (Push operation).\n");
printf("2. Delete from stack (Pop operation).\n");
printf("3. Print top element of stack.\n");
printf("4. Check if stack is empty.\n");
printf("5. Traverse stack.\n");
printf("6. Exit.\n");
printf("Enter your choice.\n");
scanf("%d",&choice);
switch ( choice )
{
case 1:
if ( top == MAX_SIZE - 1 )
printf("Error: Overflow\n\n");
else
{
printf("Enter the value to insert.\n");

Dept. Of CSE 30 CS426


scanf("%d",&element);
push(element);
}
break;

case 2:
if ( top == -1 )
printf("Error: Underflow.\n\n");
else
{
element = pop();
printf("Element removed from stack is %d.\n", element);
}
break;
case 3:
if(!is_empty())
{
element = top_element();
printf("Element at the top of stack is %d\n\n", element);
}
else
printf("Stack is empty.\n\n");
break;
case 4:
if(is_empty())
printf("Stack is empty.\n\n");
else
printf("Stack is not empty.\n\n");
break;
case 5:
traverse();
break;
case 6:
exit(0);
}
}
}
void push(int value)
{
top++;
stack[top] = value;
}
int pop()
{

Dept. Of CSE 31 CS426


int element;
if ( top == -1 )
return top;
element = stack[top];
top--;
return element;
}
void traverse()
{
int d;
if ( top == - 1 )
{
printf("Stack is empty.\n\n");
return;
}
printf("There are %d elements in stack.\n", top+1);
for ( d = top ; d >= 0 ; d-- )
printf("%d\n", stack[d]);
printf("\n");
}
int is_empty()
{
if ( top == - 1 )
return 1;
else
return 0;
}
int top_element()
{
return stack[top];
}

Dept. Of CSE 32 CS426


Week #5
Overview of Queue Using Array and Linked List.

Queue:-

A queue is a particular kind of abstract data type or 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, known as en-queue, and removal of entities
from the front terminal position, known as de-queue. 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 once a new element
is added, all elements that were added before have to be removed before the new element can
be removed. Often a peek or front operation is also entered, returning the value of the front
element without de-queuing it. A queue is an example of a linear data structure, or more
abstractly a sequential collection.

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 CSE 33 CS426


Experiment No 13

OBJECTIVE

Implement Queue using Array.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to perform Overflow, Underflow and Traverse Queue Elements.
 Students perform Queue using Linked List.

#include<stdio.h>
#include<conio.h>
#define MAX 10
void insert(int);
int del();
int queue[MAX], rear=0, front=0;
void display();
int main()
{
char ch , a='y';
int choice, token;
printf("1.Insert");
printf("\n2.Delete");
printf("\n3.show or display");
do
{
printf("\nEnter your choice for the operation: ");
scanf("%d",&choice);
switch(choice)
{
case 1: insert(token);
display();
break;
case 2:
token=del();
printf("\nThe token deleted is %d",token);
display();
break;
case 3:
display();
break;
default:
printf("Wrong choice");
Dept. Of CSE 34 CS426
break;
}
printf("\nDo you want to continue(y/n):");
ch=getch();
}
while(ch=='y'||ch=='Y');
getch();
}
void display()
{
int i;
printf("\nThe queue elements are:");
for(i=rear;i<front;i++)
{
printf("%d ",queue[i]);
}
}
void insert(int token)
{
char a;
if(rear==MAX)
{
printf("\nQueue full");
return;
}
do
{
printf("\nEnter the token to be inserted:");
scanf("%d",&token);
queue[front]=token;
front=front+1;
printf("do you want to continue insertion Y/N");
a=getch();
}
while(a=='y');
}
int del()
{
int t;
if(front==rear)
{
printf("\nQueue empty");
return 0;
}

Dept. Of CSE 35 CS426


rear=rear+1;
t=queue[rear-1];
return t;
}

Circular Queue:-

In a standard queue data structure re-buffering problem occurs for each de-queue operation.
To solve this problem by joining the front and rear ends of a queue to make the queue as a
circular queue
Circular queue is a linear data structure. It follows FIFO principle.

 In circular queue the last node is connected back to the first node to make a circle.
 Circular linked list fallow the First In First Out principle
 Elements are added at the rear end and the elements are deleted at front end of the
queue
 Both the front and the rear pointers points to the beginning of the array.
 It is also called as “Ring buffer”.
 Items can inserted and deleted from a queue in O (1) time.

Circular Queue can be created in three ways they are


· Using single linked list
· Using double linked list
· Using arrays

Using single linked list:


It is an extension for the basic single linked list. In circular linked list Instead of storing a
Null value in the last node of a single linked list, store the address of the 1st node (root)
forms a circular linked list. Using circular linked list it is possible to directly traverse to the
first node after reaching the last node.

Using array:
In arrays the range of a subscript is 0 to n-1 where n is the maximum size. To make the array
as a circular array by making the subscript 0 as the next address of the subscript n-1 by using
the formula subscript = (subscript +1) % maximum size. In circular queue the front and rear
pointer are updated by using the above formula.

Dept. Of CSE 36 CS426


Experiment No 14

OBJECTIVE

Implement Circular Queue using Array

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to perform Overflow, Underflow and Traverse Circular Queue
Elements.

#include<stdio.h>
#define max 5
int front,rear,q[max];
void enqueue(void);
void dequeue(void);
void qdisplay(void);
void main(void)
{
int c;
clrscr();
front=rear=-1;
do
{
printf("1:insert\n2:deletion\n3:display\n4:exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:enqueue();break;
case 2:dequeue();break;
case 3:qdisplay();break;
case 4:printf("pgm ends\n");break;
default:printf("wrong choice\n");break;
}
}while(c!=4);
getch();
}
void enqueue(void)
{
int x;
if((front==0&&rear==max-1)||(front==rear+1))
{
printf("Queue is overflow\n");return;

Dept. Of CSE 37 CS426


}
if(front==-1)
{
front=rear=0;
}
else
{
if(rear==max-1)
{
rear=0;
}
else
{
rear++;
}
}
printf("enter the no:\n");
scanf("%d",&x);
q[rear]=x;
printf("%d succ. inserted\n",x);
return;
}
void dequeue(void)
{
int y;
if(front==-1)
{
printf("q is underflow\n");return;
}
y=q[front];
if(front==rear)
{
front=rear=-1;
}
else
{
if(front==max-1)
{
front=0;
}
else
{
front++;
}

Dept. Of CSE 38 CS426


}
printf("%d succ. deleted\n",y);
return;
}
void qdisplay(void)
{
int i,j;
if(front==rear==-1)
{
printf("q is empty\n");return;
}
printf("elements are :\n");
for(i=front;i!=rear;i=(i+1)%max)
{

printf("%d\n",q[i]);
}
printf("%d\n",q[rear]);
return;
}

Dept. Of CSE 39 CS426


Week #6
Overview of Tree.

Tree:-

A tree is a widely used abstract data type (ADT) or data structure implementing this ADT
that simulates a hierarchical tree structure, with a root value and sub-trees of children,
represented as a set of linked nodes.
A tree data structure can be defined recursively (locally) as a collection of nodes (starting at a
root node), where each node is a data structure consisting of a value, together with a list of
references to nodes (the "children"), with the constraints that no reference is duplicated, and
none points to the root.
Alternatively, a tree can be defined abstractly as a whole (globally) as an ordered tree, with a
value assigned to each node. Both these perspectives are useful: while a tree can be analyzed
mathematically as a whole, when actually represented as a data structure it is usually
represented and worked with separately by node (rather than as a list of nodes and an
adjacency list of edges between nodes, as one may represent a digraph, for instance). For
example, looking at a tree as a whole, one can talk about "the parent node" of a given node,
but in general as a data structure a given node only contains the list of its children, but does
not contain a reference to its parent

There are three types of depth-first traversal: pre-order, in-order, and post-order. For a binary
tree, they are defined as operations recursively at each node, starting with the root node as
follows:

Pre-order
 Visit the root.
 Traverse the left subtree.
 Traverse the right subtree.

In-order (symmetric)
 Traverse the left subtree.
 Visit the root.
 Traverse the right subtree.

Post-order
 Traverse the left subtree.
 Traverse the right subtree.
 Visit the root.

Dept. Of CSE 40 CS426


The trace of a traversal is called a sequentialisation of the tree. No one sequentialisation
according to pre-, in- or post-order describes the underlying tree uniquely. Given a tree with
distinct elements, either pre-order or post-order paired with in-order is sufficient to describe
the tree uniquely. However, pre-order with post-order leaves some ambiguity in the tree
structure.

Dept. Of CSE 41 CS426


Experiment No 15

OBJECTIVE

Implement Tree and Tree Traversal Using:-In-order, Pre-order, Post-order

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to perform Traverse of Tree Like-In-Order, Pre-Order, Post-Order. 

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct tree
{
int head;
struct tree *l, *r;
};
struct tree *r,*t;
int ch1,n,flag=0,in;
void main()
{
char ch='y';
r=NULL;
clrscr();
while (ch=='y')
{
clrscr();
printf("\n 1.Creat tree");
printf("\n 2.Traverse In-Order");
printf("\n 3.Traverse Pre-Order");
printf("\n 4.Traverse Post-Order");
printf("\n 5.Exit");
printf("\n Enter chioce");
scanf("%d",&ch1);
switch (ch1)
{
case 1:
if (insert(&r)==0)
break;
case 2:
printf("\n\n Left,Root,Right");
inorder(r);
getch();
Dept. Of CSE 42 CS426
break;
case 3:
printf("\n \n Root,Left,Right");
preorder(r);
getch();
break;
case 4:
printf("\n\n Left,Right,Root");
postorder(r);
getch();
break;
case 5:
exit();
default :
printf(" Wrong Choice ");
}// switch close
}// while clsoe
getch();
} //main close

insert(struct tree **ptr)


{
if (*ptr==NULL)
{
*ptr=malloc (sizeof(struct tree));
printf("\n Enter the element ");
scanf("%d",&n);
(*ptr)->head=n;
(*ptr)->l=NULL;
(*ptr)->r=NULL;
return(0);
}
//flag=1;}
else
clrscr();
printf("\n1. Left Element");
printf("\n2. Right Element");
printf("\n3. Exit");
printf("\n Enter choice");
scanf("%d",&in);
switch(in)
{
case 1:
insert(&(*ptr)->l);

Dept. Of CSE 43 CS426


break;
case 2:
insert(&(*ptr)->r);
break;
case 3:
break;
default:
printf("\n Choice is wrong");
}// switch
return(0);
} //fun close

inorder(struct tree *ptr)


{
if(ptr!=NULL)
{
inorder(ptr->l);
printf("%d",ptr->head);
inorder(ptr->r);
} // if close
return(0);
} //fun close

preorder(struct tree *ptr)


{
if (ptr!=NULL)
{
printf("%d",ptr->head);
preorder(ptr->l);
preorder(ptr->r);
} // if close
return(0);
} //fun close

postorder(struct tree *ptr)


{
if (ptr!=NULL)
{
postorder(ptr->l);
postorder(ptr->r);
printf("%d",ptr->head);
} // if close
return(0);
} //fun close

Dept. Of CSE 44 CS426


Week # 7
Overview of Graph.

Graph:-

BFS:-
In graph theory, breadth-first search (BFS) is a strategy for searching in a graph when search
is limited to essentially two operations: (a) visit and inspect a node of a graph; (b) gain
access to visit the nodes that neighbor the currently visited node. The BFS begins at a root
node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it
inspects their neighbor nodes which were unvisited, and so on. Compare BFS with the
equivalent, but more memory-efficient Iterative deepening depth-first search and contrast
with depth-first search.

DFS:-
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data
structures. One starts at the root (selecting some arbitrary node as the root in the case of a
graph) and explores as far as possible along each branch before backtracking.

Dept. Of CSE 45 CS426


Experiment No 16

OBJECTIVE

Implement BFS Traversal.

After completing this experiment you will be able to:

 Students should able to write logic of program.


 Understand how to perform Graph Traversal like BFS.

#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<math.h>
void input();
void output();
int db(int);
void BFS(struct tree *);
struct tree
{
char node[10];
struct tree *left,*right;
} *temp, *root=NULL,*t,*q[25];
int d,a[10],jj,ii,ti,b,fi,ri;
char ch[10];
void main()
{
clrscr();
input();
output();
getch();
}
void input()
{
int n,m,r,i,f;
printf("Enter the no of depth:-");
scanf("%d",&d);
n=pow(2,d+1)-1;
for(i=1;i<=n;i++)
{
printf("Enter the %d node name:-",i);
scanf("%s",ch);

Dept. Of CSE 46 CS426


temp=(struct tree *)malloc(sizeof(struct tree));
strcpy(temp->node,ch);
temp->left=NULL;
temp->right=NULL;
if(root==NULL)
{
root=temp;
}
else
{
t=root;
r=db(i);
for(f=1;f<r;f++)
{
if(a[f]==0)
{
t=t->left;
}
else
{
t=t->right;
}
}
if(a[r]==0)
{
t->left=temp;
}
else
{
t->right=temp;
}
}
}
}
void output()
{
t=root;
printf("\n Enter the name Goal:-");
scanf("%s",ch);
BFS(t);
}
int db(int n)
{
int ji=0;

Dept. Of CSE 47 CS426


while(n!=0)
{
a[ji++]=n%2;
n=n/2;
}
for(ii=0,b=ji-1;ii<b;ii++,b--)
{
ti=a[ii];
a[ii]=a[b];
a[b]=ti;
}
ji--;
return ji;
}
void BFS(struct tree *t)
{
int yes=0,index;
fi=0;
ri=1;
q[fi]=t;
printf("\n Breadth First search:-\n");
while(fi<ri)
{
t=q[fi++];
printf("%s",t->node);
if(strcmp(t->node,ch)==0)
{
yes=1;
index=fi;
}
if(t->left!=NULL)
{
q[ri++]=t->left;
}
if(t->right!=NULL)
{
q[ri++]=t->right;
}
}
if(yes==1)
printf("\n Goal State Are Present at Node %d",index);
else
printf("\n Goal State Are Not Present");
}

Dept. Of CSE 48 CS426


DFS:-
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data
structures. One starts at the root (selecting some arbitrary node as the root in the case of a
graph) and explores as far as possible along each branch before backtracking.
Experiment No 17

OBJECTIVE

Implement DFS Traversal.

After completing this experiment you will be able to:


 Students should able to write logic of program. 
 Understand how to perform Graph Traversal like DFS. 

#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<math.h>
void input();
void output();
int db(int);
void DFS(struct tree *);
struct tree
{
char node[10];
struct tree *left,*right;
} *temp, *root=NULL,*t,*s[25];
int d,a[10],jj,ii,ti,b,top;
char ch[10];
void main()
{
clrscr();
input();
output();
getch();
}
void input()
{
int n,m,r,i,f;
printf("Enter the no of depth:-");
scanf("%d",&d);
n=pow(2,d+1)-1;
for(i=1;i<=n;i++)
{
Dept. Of CSE 49 CS426
printf("Enter the %d node name:-",i);
scanf("%s",ch);
temp=(struct tree *)malloc(sizeof(struct tree));
strcpy(temp->node,ch);
temp->left=NULL;
temp->right=NULL;
if(root==NULL)
{
root=temp;
}
else
{
t=root;
r=db(i);
for(f=1;f<r;f++)
{
if(a[f]==0)
{
t=t->left;
}
else
{
t=t->right;
}
}
if(a[r]==0)
{
t->left=temp;
}
else
{
t->right=temp;
}
}
}
}
void output()
{
t=root;
printf("\n Enter the name Goal:-");
scanf("%s",ch);
DFS(t);
}
int db(int n)

Dept. Of CSE 50 CS426


{
int ji=0;
while(n!=0)
{
a[ji++]=n%2;
n=n/2;
}
for(ii=0,b=ji-1;ii<b;ii++,b--)
{
ti=a[ii];
a[ii]=a[b];
a[b]=ti;
}
ji--;
return ji;
}
void DFS(struct tree *t)
{
int yes=0,top=1;
s[top]=t;
printf("\n Depth First search:-\n");
while(top>0)
{
t=s[top];
top--;
printf("%s",t->node);
if(strcmp(t->node,ch)==0)
{
yes=1;
}
if(t->left!=NULL)
{
s[++top]=t->left;
}
if(t->right!=NULL)
{
s[++top]=t->right;
}
}
if(yes==1)
printf("\n Goal State Are Present");
else
printf("\n Goal State Are Not Present");
}

Dept. Of CSE 51 CS426


Week # 8

Overview pattern matching of a Sub string.


String searching algorithms, sometimes called string matching algorithms, are an important
class of string algorithms that try to find a place where one or several strings (also called
patterns) are found within a larger string or text.
Let Σ be an alphabet (Finite set). Formally, both the pattern and searched text are vectors of
elements of Σ. The Σ may be a usual human alphabet (for example, the letters A through Z in
the Latin alphabet). Other applications may use binary alphabet (Σ = {0, 1}) or DNA
alphabet (Σ = {A, C, G, T}) in bio informatics.
In practice, how the string is encoded can affect the feasible string search algorithms. In
particular if a variable width encoding is in use, then it is slow (time proportional to N)
to find the Nth character. This will significantly slow down many of the more advanced
search algorithms. A possible solution is to search for the sequence of code units instead, but
doing so may produce false matches unless the encoding is specifically designed to avoid it.

Experiment No 18

OBJECTIVE

Implement Pattern matching using sub string.

After completing this experiment, you will be able to:

 Students should able to write logic of program.


 Understand how to perform Function for string matching using sub string.

#include <stdio.h>
#include <string.h>
int match(char [], char []);
int main()
{
char a[100], b[100];
int position;
printf("Enter some text\n");
gets(a);
printf("Enter a string to find\n");
gets(b);
position = match(a, b);
if(position != -1)
{

Dept. Of CSE 52 CS426


printf("Found at location %d\n", position + 1);
}
else
{
printf("Not found.\n");
}
return 0;
}
int match(char text[], char pattern[])
{
int c, d, e, text_length, pattern_length, position = -1;
text_length = strlen(text);
pattern_length = strlen(pattern);
if (pattern_length > text_length)
{
return -1;
}
for (c = 0; c <= text_length - pattern_length; c++)
{
position = e = c;
for (d = 0; d < pattern_length; d++)
{
if (pattern[d] == text[e])
{
e++;
}
else
{
break;
}
}
if (d == pattern_length)
{
return position;
}
}
return -1;
}

Dept. Of CSE 53 CS426

You might also like