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

Ds Final Lab Report

The document describes the results of various data structure algorithms implemented and tested by a student. It includes linear search, binary search, string operations, two pattern matching algorithms, array operations including creation, insertion and deletion, and finding the largest two elements in an array.

Uploaded by

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

Ds Final Lab Report

The document describes the results of various data structure algorithms implemented and tested by a student. It includes linear search, binary search, string operations, two pattern matching algorithms, array operations including creation, insertion and deletion, and finding the largest two elements in an array.

Uploaded by

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

LAB REPORT

DATA STRUCTURE
CSE 156
Date of Submission: 15 February, 2023

Submitted To
Dr. Md. Golam Moazzam
Professor
Department of Computer Science and Engineering
Jahangirnagar University

Submitted By
Zakia Binta Syeed
Registration No: 20220655008
Class Roll: 402
Session: 2021-2022
Department of Computer Science and Engineering
Jahangirnagar University

Jahangirnagar University
Savar, Dhaka-1342
Data Structure Lab
 Linear Search
 Binary Search
 String Operation
Menu Driven
(i)Concatenation
(ii)Length
(iii) Indexing
(iv)Substring
 First Pattern Matching Algorithm,
Second Pattern Matching Algorithm
 Array Operation
(i)Create
(ii)Insertion
(iii)Deletion
 Linked List
Menu Driven
(i)Create
(ii)Insert
(iii)Delete
(iv)Search
 Stack
(i)Menu Driven (push, pop)
(ii)Infix to Postfix
(ii)Infix to Postfix Evaluation
 Quick Sort
 Queue (push, pop)
 Tree Menu Driven
 Create a binary tree by taking input from user
Output In order Traversal of that tree
 Graph by taking input from user
Find Out indegree and outdegree of all vertices in a graph
Find Path Matrix
Find Shortest Path Matrix
1.Linear Search

Code:

#include <iostream>
using namespace std;

int search(int arr[], int N, int x)


{
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}

// Driver code
int main()
{

int N ,x ;
cout<<"How many elements do you want in an array : ";
cin>> N ;
int arr[N];
cout<<"\nEnter "<<N<<" elements : " ;
for(int i=0 ; i<N ; i++)
cin>>arr[i];
cout<<"\nEnter Your searching elements : " ;
cin>> x ;
cout<<endl ;
// Function call
int result = search(arr, N, x);
(result == -1)
? cout << "Element is not present in array\n\n"
: cout << "Element is present at index " << result<<endl ;
return 0;
}

Input and Output :


2.Binary Search
Code:

#include <iostream>
using namespace std;

int binarySearch(int arr[], int l, int r, int x)


{
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// If we reach here, then element was not present
return -1;
}
// Driver code
int main()
{
int n ,x ;
cout<<"How many elements do you want in an array : ";
cin>> n ;
int arr[n];
cout<<"\nEnter "<<n<<" elements : " ;
for(int i=0 ; i<n ; i++)
cin>>arr[i];
cout<<"\nEnter Your searching elements : " ;
cin>> x ;

int result = binarySearch(arr, 0, n - 1, x);


(result == -1)
? cout << "Element is not present in array\n"
: cout << "Element is present at index " << result<<endl;
return 0;
}

Input and Output :


3(i) Find Largest and Second Largest element
Code:
#include<iostream>
using namespace std ;
int main(){

int arr[10000], size , i ;


int max1 , max2 ;
cout<<"Enter the size of array : " ;
cin>> size ;
cout<<"\nEnter the elements of array : ";
for(int i=0 ; i<size ; i++)
cin>>arr[i];

cout<<endl ;

max1= arr[0];

for(int i=0 ; i<size ; i++){

if(arr[i]>max1){
max2=max1 ;
max1=arr[i];
}
else if(arr[i]>max2 && arr[i]<max1){
max2=arr[i];
}

cout<<"\nFirst largest number : "<<max1<<endl ;


cout<<"\nSecond largest number : "<<max2<<endl ;

return 0 ;
}
Input and Output :

3.(ii)Find largest and Second largest using Bubble Sort

Code:

#include<iostream>
#include <bits/stdc++.h>
using namespace std;

void bubbleSort(int arr[], int n)


{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}

if (swapped == false)
break;
}
}

// Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << " " << arr[i];
}

int main()
{

int N ;
cout<<"How many elements do you want in an array : ";
cin>> N ;
int arr[N];
cout<<"\nEnter "<<N<<" elements : " ;
for(int i=0 ; i<N ; i++)
cin>>arr[i];
cout<<endl ;
bubbleSort(arr, N);
cout << "Sorted array: \n";
printArray(arr, N);
cout<<"\nFirst largest number : "<<arr[N-1]<<endl ;
cout<<"\nSecond largest number : "<<arr[N-2]<<endl ;

return 0;
}

Input and Output :


4.String Operation
Menu Driven: (i) Concatenation, (ii) Length, (iii) Indexing, (iv) Substring

Code:

#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2, result;
int choice, index, length;

do {
cout << "String Operation Menu:" << endl;
cout << "1. Concatenation" << endl;
cout << "2. Length" << endl;
cout << "3. Indexing" << endl;
cout << "4. Substring" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch(choice) {
case 1: cout<<"\n\t\tInput\n"<<endl ;
cout << "Enter string 1: ";
cin >> str1;
cout << "Enter string 2: ";
cin >> str2;
result = str1 + str2;
cout<<"\n\t\tOutput\n"<<endl ;
cout << "Concatenation string: " << result << endl;
break;

case 2:
cout<<"\t\tInput\n"<<endl ;

cout << "Enter the string: ";


cin >> str1;
length = str1.length();
cout<<"\n\t\tOutput\n"<<endl ;
cout << "Length of the string: " << length << endl;
break;

case 3:
cout<<"\n\t\tInput\n"<<endl ;
cout << "Enter the string: ";
cin >> str1;
cout << "Enter the index: ";
cin >> index;
if (index >= 0 && index < str1.length()) {
cout<<"\n\t\tOutput\n"<<endl ;
cout << "Character at index " << index << ": " << str1[index] << endl;
} else {
cout<<"\n\t\tOutput\n"<<endl ;
cout << "Invalid index!" << endl;
}
break;

case 4:
cout<<"\n\t\tInput\n"<<endl ;

cout << "Enter the string: ";


cin >> str1;
cout << "Enter starting index: ";
cin >> index;
cout << "Enter length of substring: ";
cin >> length;
cout<<"\n\t\Output\n"<<endl ;

if (index >= 0 && index + length <= str1.length()) {


string sub = str1.substr(index, length);
cout << "Substring: " << sub << endl;
} else {
cout << "Invalid range!" << endl;
}
break;
case 5:
cout<<"\n\t\tOutput\n"<<endl ;
cout << "Exiting program..." << endl;
break;
default:
cout<<"\n\t\tOutput\n"<<endl ;
cout << "Invalid choice! Please try again." << endl;
break;
}
cout<<endl ;
} while (choice != 5);
return 0 ;
}
Input and Output :
5.(i)First pattern matching algorithm

Code

#include <iostream>
#include <string>

using namespace std;


int patternMatch(const string& text, const string& pattern) {
int rt=-1 ;
int n = text.size();
int m = pattern.size();
for (int i = 0; i <= n-m; i++) {
int j;
/* For current index i, check for pattern match */
for (j = 0; j < m; j++)
if (text[i + j] != pattern[j])
break;
if (j == m) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]

cout << "Pattern found at index " << i << endl;


rt=0 ;
}
return rt ;
}

int main() {
string text, pattern;
cout << "Enter the text: ";
getline(cin, text);
cout << "Enter the pattern: ";
getline(cin, pattern);

int index = patternMatch(text, pattern);


//int patternMatch(const string& text, const string& pattern)
if (index == -1) {

cout << "Pattern not found in the text." << endl;


}

return 0;
}
Input and Output :
5.(ii) Second pattern matching algorithm code
Code:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

// Function to compute the prefix function for the pattern


vector<int> computePrefix(const string& pattern) {
int m = pattern.size();
vector<int> prefix(m, 0);
int k = 0;

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


while (k > 0 && pattern[k] != pattern[q]) {
k = prefix[k - 1];
}
if (pattern[k] == pattern[q]) {
k++;
}
prefix[q] = k;
}
return prefix;
}

// Function to perform pattern matching using KMP algorithm


int kmpMatch(const string& text, const string& pattern) {
int rtr=-1;
int n = text.size();
int m = pattern.size();
vector<int> prefix = computePrefix(pattern);
int q = 0;

for (int i = 0; i < n; ++i) {


while (q > 0 && pattern[q] != text[i]) {
q = prefix[q - 1];
}
if (pattern[q] == text[i]) {
q++;
}
if (q == m) {
cout << "Pattern found at index: " << i - m + 1<<endl ;
rtr=0 ; // pattern found at index i - m + 1
}
}
return rtr; // pattern not found
}

int main() {
string text, pattern;
cout << "Enter the text: ";
getline(cin, text);
cout << "Enter the pattern: ";
getline(cin, pattern);

int index = kmpMatch(text, pattern);

if (index == -1) //{


// cout << "Pattern found at index: " << index << endl;
//} else {
cout << "Pattern not found in the text." << endl;
// }

return 0;
}

Input and Output :


6.Array Operation
Menu Driven (i)Create (ii)Insertion (iii) Deletion
Code:

#include <iostream>

int* arr = nullptr; // Pointer to store dynamic array


int size = 0; // Current size of the dynamic array

void createArray() {
if (arr) {
delete[] arr;
arr = nullptr;
}
std::cout << "Enter the size of the array: ";
std::cin >> size;
arr = new int[size];
std::cout << "New array created.\n";
}
void insertElement() {
if (!arr) {
std::cout << "Array is not created yet.\n";
return;
}

int element, position;


std::cout << "Enter the element to insert: ";
for(int i=0 ; i< size ; i++)
std::cin >> arr[i];
std::cout << "\nThe element to insert: ";
for(int i=0 ; i< size ; i++)
std::cout<<arr[i]<<" ";
std::cout<<"\n" ;

void deleteElement() {
if (!arr) {
std::cout << "Array is not created yet.\n";
return;
}

int position;
std::cout << "Enter the position (0-indexed) to delete from (0 to " << size - 1 << "): ";
std::cin >> position;

if (position < 0 || position >= size) {


std::cout << "Invalid position.\n";
} else {
std::cout << arr[position] << " deleted from position " << position << ".\n";
size=size-1 ;
for (int i = position; i < size; ++i) {
arr[i] = arr[i + 1];
}
}
}

void displayMenu() {
std::cout << "\nArray Operations Menu:\n";
std::cout << "1. Create Array\n";
std::cout << "2. Insert Element\n";
std::cout << "3. Delete Element\n";
std::cout << "4. Display Array\n";

std::cout << "5. Exit\n";


}

int main() {
char choice;

while (true) {
displayMenu();
std::cout << "Enter your choice: ";
std::cin >> choice;
switch (choice) {
case '1':
createArray();
break;
case '2':
insertElement();
break;
case '3':
deleteElement();
break;
case '4':
std::cout << "Current array: ";
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
std::cout << "\n";
break;
case '5':
delete[] arr;
std::cout << "Exiting the program.\n";
return 0;
default:
std::cout << "Invalid choice. Please try again.\n";
break;
}
}

return 0;
}

Input and Output :


7.Linked List
Menu Driven (i)Create (ii) Insert (iii)Delete (iv) Search
Code:
#include <iostream>
#include<string.h>
struct Node
{
int data;
Node* next;
};

class LinkedList
{
private:
Node* head;
public:
LinkedList() : head(nullptr) {}

// Function to insert a new node at the end of the linked list


void insert(int data)
{
Node* newNode = new Node();
newNode->data = data;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
Node* temp = head;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to search for an element in the linked list


bool search(int data)
{
Node* temp = head;
while (temp != nullptr)
{
if (temp->data == data)
{
return true;
}
temp = temp->next;
}
return false;
}

// Function to delete a node from the linked list


void deleteNode(int data)
{
Node* temp = head;
Node* prev = nullptr;
while (temp != nullptr && temp->data != data)
{
prev = temp;
temp = temp->next;
}
if (temp == nullptr)
{
std::cout << "Element not found in the linked list." << std::endl;
return;
}
if (prev == nullptr)
{
head = temp->next;
}
else
{
prev->next = temp->next;
}
delete temp;
std::cout << "Element deleted from the linked list." << std::endl;
}
// Function to insert a new node at a specific position in the linked list
void insertAtPosition(int data, int position) {
Node* newNode = new Node();
newNode->data = data;
newNode->next = nullptr;

if (position == 1) {
newNode->next = head;
head = newNode;
std::cout << "Element inserted at position " << position << " in the linked list." << std::endl;
return;
}

Node* temp = head;


for (int i = 1; i < position - 1 && temp != nullptr; ++i) {
temp = temp->next;
}

if (temp == nullptr) {
std::cout << "Invalid position. Element not inserted in the linked list." << std::endl;
} else {
newNode->next = temp->next;
temp->next = newNode;
std::cout << "Element inserted at position " << position << " in the linked list." << std::endl;
}
}

// Function to display the linked list


void display()
{
Node* temp = head;
while (temp != nullptr)
{
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}

// Destructor to delete all nodes in the linked list


~LinkedList()
{
Node* temp = head;
while (temp != nullptr)
{
Node* next = temp->next;
delete temp;
temp = next;
}
}
};

int main()
{
LinkedList list;
int choice, data , pos=-1,n,cnt=-1;

do { std::cout<<"\n" ;

std::cout << "Menu:\nFirst of all you creat a linked list and do other work\n";

std::cout << "1. Create a linked list\n";


std::cout << "2. Search\n";
std::cout << "3. Insert\n";
std::cout << "4. Delete\n";
std::cout << "5. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;

switch (choice)
{
case 1:

std::cout << "Enter elements to create a linked list (enter '-1' to stop taking elements): ";
while (true)
{
std::cin >> data;
if(data<0 && data != -1){
std::cout<<"Negative value cannot take in the linked list"<<std::endl<<"Try
again"<<std::endl ;
break ;
}

if (data==-1)
{
break;
}

list.insert(data);
}

// else{
// choice=1 ;
// }
if(data==-1){
std::cout << "Linked list created." << std::endl;

list.display();}
break;
case 2:
std::cout << "Enter element to search: ";
std::cin >> data;
if (list.search(data))
{
std::cout << "Element found in the linked list." << std::endl;
}
else
{
std::cout << "Element not found in the linked list." << std::endl;
}
break;
case 3:
/*std::cout << "Enter element to insert: ";
std::cin >> data >> pos;
list.insertpos(data,pos);
std::cout << "Element inserted into the linked */

int position;
std::cout << "Enter element to insert: ";
std::cin >> data;
std::cout << "Enter position to insert: ";
std::cin >> position;
if(position>0){
list.insertAtPosition(data, position);

list.display();}
else {
std::cout<<"Invalid position"<<std::endl ;
}

break;
case 4:
std::cout << "Enter element to delete: ";
std::cin >> data;
list.deleteNode(data);
list.display();

break;
case 5:
std::cout << "Exiting the program." << std::endl;
break;
default:
std::cout << "Invalid choice. Please try again." << std::endl;
}
} while (choice != 5);

return 0;
}
Input and Output :
8.Stack
(i)Menu Driven : Push , Pop
Code:
#include <iostream>
#include <stack>

using namespace std;

int main() {
stack<int> s;
int choice, value;

while (true) {
cout << "\nStack Operations Menu" << endl;
cout << "---------------------" << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display Top" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout<<"How many element you want to push into the stack : ";
int m ;
cin>>m ;
cout << "Enter the value to push: " ;

while(m--){
//cout << "Enter the value to push: ";
cin >> value;
s.push(value); }
//cout << value << " pushed into the stack." << endl;
break;

case 2:

cout<<"How many element you want to pop into the stack : ";
int p ;
cin>> p ;
if(!s.empty()) {
while(p--){
value = s.top();
s.pop();
cout << value << " popped from the stack." << endl;
}} else {
cout << "Stack is empty." << endl;
}
break;

case 3:
if (!s.empty()) {
cout << "Top of the stack: " << s.top() << endl;
} else {
cout << "Stack is empty." << endl;
}
break;

case 4:
cout << "Exiting the program." << endl;
return 0;

default:
cout << "Invalid choice. Please try again." << endl;
}
}
return 0;
}
Input and Output :
8(ii)Infix to Postfix
Code:
#include<iostream>
#include<stack>
using namespace std ;
int prec(char c)
{
if(c=='^')
return 3 ;
else if(c=='*' || c=='/')
return 2 ;
else if(c=='+' || c=='-')
return 1 ;
else
return -1 ;

string InfixToPostfix(string s)
{
stack<char> st ;
string res;

for(int i=0 ; i<s.length(); i++)


{

if((s[i]>='a' && s[i]<='z')||(s[i]>='A' && s[i]<='Z'))

res+=s[i] ;
else if(s[i]=='(')
st.push(s[i]) ;
else if(s[i]==')')
{
while(st.top()!='(' && !st.empty())
{
res+=st.top();
st.pop();
}
if(!st.empty())
st.pop();

else
{
while(!st.empty() && prec(st.top()) > prec(s[i]))
{
res+= st.top() ;
st.pop() ;
}
st.push(s[i]);
}

}
while(!st.empty())
{
res+= st.top() ;
st.pop();

return res ;
}
int main()
{
cout<<"Enter a Infix expression = " ;
string s ;
cin>>s ;
cout<<"infix to Postfix convert = " << InfixToPostfix(s) <<endl ;
return 0 ;
}

Input and Output :

8(iii)Infix to Postfix Evaluation


Code:
#include<iostream>
#include<stack>
#include<math.h>
using namespace std ;
int prec(char c)
{
if(c=='^')
return 3 ;
else if(c=='*' || c=='/')
return 2 ;
else if(c=='+' || c=='-')
return 1 ;
else
return -1 ;
}

string InfixToPostfix(string s)
{
stack<char> st ;
string res;

for(int i=0 ; i<s.length(); i++)


{

if(s[i]>='0' && s[i]<='9')

res+=s[i] ;
else if(s[i]=='(')
st.push(s[i]) ;
else if(s[i]==')')
{
while(st.top()!='(' && !st.empty())
{
res+=st.top();
st.pop();
}
if(!st.empty())
st.pop();

else
{
while(!st.empty() && prec(st.top()) > prec(s[i]))
{
res+= st.top() ;
st.pop() ;
}
st.push(s[i]);
}
}
while(!st.empty())
{
res+= st.top() ;
st.pop();

return res ;
}
int PostfixEvaluation(string s){
stack<int> st ;
for(int i=0 ; i<s.length() ; i++)
{
if(s[i]>='0' && s[i]<='9')
st.push(s[i] - '0') ;
else {
int op2= st.top();
st.pop() ;
int op1= st.top();
st.pop() ;
switch(s[i]){
case '+' :
st.push(op1+op2);
break ;
case '-' :
st.push(op1-op2);
break ;
case '*' :
st.push(op1*op2);
break ;
case '/' :
st.push(op1/op2);
break ;
case '^' :
st.push(op1^op2);
break ;

}}}
return st.top() ;
}
int main()
{

cout<<"Enter a Infix expression = " ;


string s ;
cin>>s ;
cout<<"infix to Postfix convert = " << InfixToPostfix(s) <<endl ;
string T= InfixToPostfix(s) ;
cout<<"infix to Postfix Evaluation value = " << PostfixEvaluation( T ) <<endl ;
return 0 ;

}
Input and Output :

8(iv)Quick sort
Code:
#include<iostream>
using namespace std ;
void swap(int array[],int start, int end)
{
int temp = array[start] ;
array[start] = array[end] ;
array[end] = temp ;

int Partition (int array[],int low, int high)


{
int pivot = array[high] ;
int start = low-1 ;
for(int end=low ; end<high ; end++)
{
if(array[end]<pivot)
{
start++ ;
swap(array, start,end);
}
}
swap(array,start+1,high);
return start+1 ;}
void QuickSort (int array[],int low,int high)
{

if(low<high)
{
int pivot = Partition (array,low,high) ;
QuickSort(array,low,pivot-1) ;
QuickSort(array,pivot+1, high);
}
}

int main(){
int n ;
cout<<"How much element you want = " ;
cin>> n ;
int array[n] ;
for(int i=0 ; i<n ; i++){
cin>> array[i] ;
}
QuickSort(array,0,n-1);
cout<<endl <<"After apply quick sort algorithm the array is = " <<endl ;
for(int i=0 ; i<n ; i++){
cout<<array[i]<<" " ;
}
cout<<endl ;

return 0 ;
}
Input and Output :
9.Queue (Push,Pop)
Code:
#include<iostream>
int main();
using namespace std ;
class Queue{
private :
int front , rear , *a ;
int maxsize ;
public :

Queue(){}

Queue(int size): front(-1),rear(-1), maxsize(size){ //size = s ;


a= new int[size] ;
front = rear=-1 ;
}
~Queue(){

delete[]a ;

}
int enqueue(int x){

if(rear==maxsize-1){ cout<<"Overflow"<<endl ;
}
else if(front=-1 && rear==-1){
front=rear=0 ;
a[rear]=x ;
}
else {

rear++ ;
a[rear] =x ;
}
}

int dequeue(){

if(front = -1 && rear==-1)


cout<<"Underflow"<<endl ;

else if(front==rear ){

cout<<"Deleted element is = "<<a[front] <<endl ;


front=rear=-1 ;
}

else {
cout<<"Deleted element is = "<<a[front] <<endl ;
front++ ;
}

cout<<endl <<endl ;
}
int display(){

int i ;
if(front==-1 && rear==-1)
cout<<"Queue is empty "<<endl ;
else {

cout<<" The display element is = " ;

for(i=front ; i<=rear ; i++){


cout<<a[i]<<" " ;
}
}

cout<<endl<<endl ;
}
};
int main()
{ int s ;
cout<<"Enter your Queue size : " ;
cin>> s ;
Queue queue(s) ;
int n ,x ;

cout<<endl <<endl ;
int option=1 ;
while(option !=0){
cout<< "\tIf you want to input value press 1\n\tif you delete press 2\n\tif you display press 3\n\
tif you exit press 0\n\tNow choice the option = " ;
cin>> option ;
cout<<endl <<endl ;
if(option==1){
cout<< " Put value = " ;
cin>> x ;

queue.enqueue( x) ;
}
else if(option==2)
queue.dequeue() ;

else if(option==3)
queue.display() ;

}
}
Input and Output :
10. Tree Menu Driven
(i)Create a Binary Tree by Taking User Input
(ii)OutPut InOrder Traversal Of That Tree
Code:
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left,*right;
};
struct Node *create() {
int x;
struct Node *newnode;
newnode = new Node;
cout << "Enter Data: " << endl;
cin >> x;
if(x == -1) {
return 0;
}
newnode->data = x;
cout << "Enter left child of " << x << " : " << endl;
newnode->left = create();
cout << "Enter right child of " << x << " : " << endl;
newnode->right = create();
return newnode;
}
void preorder(struct Node* root) {
if(root == NULL)
return;
cout << root->data << "->" << endl;
preorder(root->left);
preorder(root->right);
}
void inorder(struct Node* root) {
if(root == NULL)
return;
inorder(root->left);
cout << root->data << "->" << endl;
inorder(root->right);
}
void postorder(struct Node *root) {
if(root == NULL)
return;
postorder(root->left);
postorder(root->right);
cout << root->data << "-> " << endl;
}
int main() {
// int choice;
struct Node *root = NULL;
//root = NULL;
root = create();
cout << "Preorder list: " << endl;
preorder(root);
cout << "Postorder list: " << endl;
postorder(root);
cout << "Inorder list : " << endl;
inorder(root);
}

Input and Output :


11.
Graph By Taking User Input
(i)Find Out Indegree And Outdegree of all vertices in a Graph
Code:
#include <bits/stdc++.h>

using namespace std;


#define MAX 100
void cal_Degree(int vertices, int adjMatrix[MAX][MAX], int indegree[], int outdegree[])
{
for (int i = 0; i < vertices; i++) {
outdegree[i] = 0;
indegree[i] = 0;
}

for (int i = 0; i < vertices; i++) {


for (int j = 0; j < vertices; j++) {
if (adjMatrix[i][j] == 1) {
outdegree[i]++;
indegree[j]++;
}
}
}
}

int main()
{
int vertices;
cout << "Enter the number of vertices: ";
cin >> vertices;

int adjMatrix[MAX][MAX] = {0};

int edges;
cout << "Enter the number of edges: ";
cin >> edges;

cout << "Enter the edges (source and destination):\n";


for (int i = 0; i < edges; ++i) {
int src, dest;
cin >> src >> dest;
adjMatrix[src][dest] = 1;
}

int indegree[MAX], outdegree[MAX];

cal_Degree(vertices, adjMatrix, indegree, outdegree);

for (int i = 0; i < vertices; ++i)


{
cout << "Vertex " << i << " Indgree = " << indegree[i] << " Outdegree = " <<
outdegree[i] << endl;
}
return 0;
}
Input and Output :

11.Graph By Taking User Input


(ii)Find Path Matrix
Code:
#include <bits/stdc++.h>

using namespace std;

int main()
{
int m, i, j, k;
int adj[100][100], path[100][100] = {0};
cout << "Enter the number of vertices: ";
cin >> m;

cout << "Enter a "<< m << "X" << m << " size adjacency matrix: " << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
cin >> adj[i][j];
}
}

for(i = 0; i < m; i++)


{
for(j = 0; j < m; j++)
{
path[i][j] = adj[i][j];
}
}

for(k = 0; k < m; k++)


{
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
path[i][j] = path[i][j] || (path[i][k] && path[k][j]);
}
}
}

cout << "Path matrix is: " << endl;

for(i = 0; i < m; i++)


{
for(j = 0; j < m; j++)
{
cout << path[i][j] << " ";
}
cout << endl;
}
}
Input and Output :

11.Graph By Taking User Input


(ii)Find Shortest Path Matrix
Code:
#include <bits/stdc++.h>
using namespace std;
#define INF 999999
int main()
{ int m, i, j, k;
int adj[100][100], shpath[100][100] = {0};
cout << "Enter the number of vertices: ";
cin >> m;

cout << "Enter a "<< m << "X" << m << " size adjacency matrix: " << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
cin >> adj[i][j];
}
}

for(i = 0; i < m; i++)


{
for(j = 0; j < m; j++)
{
if(adj[i][j] == 0)
shpath[i][j] = INF;
else
shpath[i][j] = adj[i][j];
}
}

for(k = 0; k < m; k++)


{
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
shpath[i][j] = min(shpath[i][j] , (shpath[i][k] + shpath[k][j]));
}
}
}

cout << "Shortest Path matrix is: " << endl;

for(i = 0; i < m; i++)


{
for(j = 0; j < m; j++)
{
if(shpath[i][j] == INF)
cout << "INF ";
else
cout << shpath[i][j] << " ";
}
cout << endl;
}
}
Input and Output :

You might also like