0% found this document useful (0 votes)
9 views54 pages

Data Structures Lab File Sem-2 Hard

This document is a lab file for the Data Structures course at Netaji Subhas University of Technology, detailing various programming experiments. It includes submissions from multiple students and outlines tasks such as implementing stacks and queues, converting infix expressions to postfix, and removing duplicates from linked lists. Each experiment contains code snippets and expected outputs.
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)
9 views54 pages

Data Structures Lab File Sem-2 Hard

This document is a lab file for the Data Structures course at Netaji Subhas University of Technology, detailing various programming experiments. It includes submissions from multiple students and outlines tasks such as implementing stacks and queues, converting infix expressions to postfix, and removing duplicates from linked lists. Each experiment contains code snippets and expected outputs.
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

NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY

SEM-2 BRANCH
BATCH 23-27 IT-1

DATA STRUCTURES
LAB FILE

COURSE CODE: ITITC201

SUBMITTED BY:
NAME ROLL NO.
Shrikar Teja Yeeli 2023UIT3001
Anshul Dhoptey 2023UIT3016
Lisha Angral 2023UIT2018
Armaan Barak 2023UIT3035
Anmol Virmani 2023UIT3040

SUBMITTED TO: DR. APOORVI SOOD


NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY

SEM-2 BRANCH
BATCH 23-27 IT-1

DATA STRUCTURES
LAB FILE

COURSE CODE: ITITC201

SUBMITTED BY:
NAME ROLL NO.
Shrikar Teja Yeeli 2023UIT3001

SUBMITTED TO: DR. AMARJIT MALHOTRA


and MR. KARAN GARG
NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY

SEM-2 BRANCH
BATCH 23-27 IT-1

DATA STRUCTURES
LAB FILE

COURSE CODE: ITITC201

SUBMITTED BY:
NAME ROLL NO.
Anshul Dhoptey 2023UIT3016

SUBMITTED TO: DR. AMARJIT MALHOTRA


and MR. KARAN GARG
NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY

SEM-2 BRANCH
BATCH 23-27 IT-1

DATA STRUCTURES
LAB FILE

COURSE CODE: ITITC201

SUBMITTED BY:
NAME ROLL NO.
Lisha Angral 2023UIT2018

SUBMITTED TO: DR. AMARJIT MALHOTRA


and MR. KARAN GARG
NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY

SEM-2 BRANCH
BATCH 23-27 IT-1

DATA STRUCTURES
LAB FILE

COURSE CODE: ITITC201

SUBMITTED BY:
NAME ROLL NO.
Armaan Barak 2023UIT3035

SUBMITTED TO: DR. AMARJIT MALHOTRA


and MR. KARAN GARG
NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY

SEM-2 BRANCH
BATCH 23-27 IT-1

DATA STRUCTURES
LAB FILE

COURSE CODE: ITITC201

SUBMITTED BY:
NAME ROLL NO.
Anmol Virmani 2023UIT3040

SUBMITTED TO: DR. AMARJIT MALHOTRA


and MR. KARAN GARG
INDEX
[Link]. TITLE Date Page Sign
1. Write a program to implement two stacks in 3
an array.
2. Write a program to implement stack using 6
Linked List.
3. Write a program to convert an infix 8
expression to post fix and evaluate the post
fix expression using stack.
4. Write a program to implement queue using 11
array.

5. Write a program to implement priority 13


queue using linked list.

6. Write a program to display a singly linked list 16


in reverse order.

7. Write a program to remove duplicates in a 19


singly linked list.

8. Write a program to convert a binary tree into 22


doubly linked list.

9. Write a program to check whether the given 26


binary search tree is balanced or not.

10. Write a program to traverse a directed graph 29


using DFS.

11. Write a program for quick sort. 32


EXPERIMENT-1

Q. Write a program to implement two stacks in an array.

CODE:

#include <iostream>
using namespace std;

class twoStacks {
int* arr;
int size;
int top1, top2;

public:
// Constructor
twoStacks(int n) {
size = n;
arr = new int[n];
top1 = n / 2 + 1;
top2 = n / 2;
}

// Method to push an element x to stack1


void push1(int x) {
// There is at least one empty
// space for new element
if (top1 > 0) {
top1--;
arr[top1] = x;
} else {
cout << "Stack Overflow\n";
return;
}
}
// Method to push an element
// x to stack2
void push2(int x) {

// There is at least one empty


// space for new element
if (top2 < size - 1) {
top2++;
arr[top2] = x;
} else {
cout << "Stack Overflow\n";
return;
}
}

// Method to pop an element from first stack


int pop1() {
if (top1 <= size / 2) {
int x = arr[top1];
top1++;
return x;
} else {
cout << "Stack UnderFlow\n";
exit(1);
}
}

// Method to pop an element


// from second stack
int pop2() {
if (top2 >= size / 2 + 1) {
int x = arr[top2];
top2--;
return x;
} else {
cout << "Stack UnderFlow\n";
exit(1);
}
}
};
/* Driver program to test twoStacks class */
int main() {
twoStacks ts(5);
ts.push1(5);
ts.push2(10);
ts.push2(15);
ts.push1(11);
ts.push2(7);
cout << "Popped element from stack1 is " << ts.pop1() << endl;
ts.push2(40);
cout << "Popped element from stack2 is " << ts.pop2() << endl;
return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-2

Q. Write a program to implement stack using Linked List.

CODE:
#include <iostream>
using namespace std;

// Structure of the Node


struct Node {
int data;

Node *link;
};

Node *top = NULL;

bool isempty() {
if (top == NULL) {
return true;
} else {
return false;
}
}

void push(int value) {


Node *ptr = new Node();
ptr->data = value;
ptr->link = top;
top = ptr;
}

void pop() {
if (isempty()) {
cout << "Stack is Empty";
} else {
Node *ptr = top;
top = top->link;
delete (ptr);
}
}
void showTop() {
if (isempty()) {
cout << "Stack is Empty";
} else {
cout << "Element at top is : " << top->data << endl;
}
}

void displayStack() {
if (isempty()) {
cout << "Stack is Empty";
} else {
Node *temp = top;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->link;
}
cout << "\n";
}
}

// Main function
int main() {

push(1);
push(2);
push(3);
push(4);
showTop();
pop();
showTop();
displayStack();
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-3
Q. Write a program to convert an infix expression to post
fix and evaluate the post fix expression using stack.

CODE:
#include <iostream>
#include <stack>
#include <string>
#include <cctype>

using namespace std;

int precedence(char op) {


if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
else
return 0;
}

string infixToPostfix(const string& infix) {


stack<char> opStack;
string postfix;

for (char ch : infix) {


if (isdigit(ch) || isalpha(ch)) {
postfix += ch;
} else if (ch == '(') {
[Link](ch);
} else if (ch == ')') {
while (![Link]() && [Link]() != '(') {
postfix += [Link]();
[Link]();
}
[Link](); // Discard '('
} else {
while (![Link]() && precedence([Link]()) >=
precedence(ch)) {
postfix += [Link]();
[Link]();
}
[Link](ch);
}
}

while (![Link]()) {
postfix += [Link]();
[Link]();
}

return postfix;
}

int evaluatePostfix(const string& postfix) {


stack<int> operandStack;

for (char ch : postfix) {


if (isdigit(ch)) {
[Link](ch - '0');
} else {
int operand2 = [Link]();
[Link]();
int operand1 = [Link]();
[Link]();
switch (ch) {
case '+':
[Link](operand1 + operand2);
break;
case '-':
[Link](operand1 - operand2);
break;
case '*':
[Link](operand1 * operand2);
break;
case '/':
[Link](operand1 / operand2);
break;
}
}
}

return [Link]();
}
int main() {
string infixExpression;
cout << "Enter the infix expression: ";
getline(cin, infixExpression);

string postfixExpression = infixToPostfix(infixExpression);


cout << "Postfix expression: " << postfixExpression << endl;

int result = evaluatePostfix(postfixExpression);


cout << "Result: " << result << endl;

return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-4

Q. Write a program to implement queue using array.


CODE:

#include <iostream>
using namespace std;
int queue[100], n = 100, front = -1, rear = -1;

void Insert(int val) {

if (rear == n - 1) {
cout << "Queue Overflow" << endl;
} else {
if (front == -1) {
front = 0;
}
rear++;
queue[rear] = val;
}
}

void Delete() {
if (front == -1 || front > rear) {
cout << "Queue Underflow ";
return;
} else {
cout << "Element deleted from queue is : " << queue[front] <<
endl;
front++;
}
}
void Display() {
if (front == -1) {
cout << "Queue is empty" << endl;
} else {
cout << "Queue elements are : ";
for (int i = front; i <= rear; i++)
cout << queue[i] << " ";
cout << endl;
}
}

int main() {
Insert(1);
Insert(2);
Insert(3);
Insert(4);

Display();
Delete();
Display();

return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-5

Q. Write a program to implement priority queue using


linked list.

CODE:
#include <iostream>
using namespace std;
struct Node
{
int data;
int priority;
Node *next;
};

Node *front = NULL;

void insert(int data, int priority)


{

Node *temp, *curr, *pre = NULL;

temp = new Node;


temp->data = data;
temp->priority = priority;

if (front == NULL or priority >= front->priority) {


temp->next = front;
front = temp;
} else {
curr = front;

while (curr and priority <= curr->priority) {


pre = curr;
curr = curr->next;
}
temp->next = pre->next;
pre->next = temp;
}
}

void Delete() {
if (front == NULL) {
cout << "Priority Queue is underflow" << endl;
return;
} else {
Node *temp;
temp = front;

cout << "Deleted item is " << temp->data << endl;

front = temp->next;
free(temp);
}
}

void display() {
if (front == NULL) {
cout << "Priority-Queue is empty" << endl;
}

Node *curr = front;

cout << "\nPriority-Queue elements are : ";

while (curr) {
cout << curr->data << " ";
curr = curr->next;
}

cout << endl;

return;
}

void peak() {
cout << "Peak element is :" << front->data << endl;
}
int main()
{
insert(2, 9);
insert(3, 4);
insert(6, 8);

display();

peak();

Delete();
Delete();
display();

return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-6

Q. Write a program to display a singly linked list in


reverse order.

CODE:

#include <iostream>
using namespace std;

/* Link list node */


struct Node {
int data;
struct Node* next;
Node(int data)
{
this->data = data;
next = NULL;
}
};

struct LinkedList {
Node* head;
LinkedList() { head = NULL; }

/* Function to reverse the linked list */


void reverse()
{
// Initialize current, previous and next pointers
Node* current = head;
Node *prev = NULL, *next = NULL;

while (current != NULL) {


// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
head = prev;
}

/* Function to print linked list */


void print()
{
struct Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}

void push(int data)


{
Node* temp = new Node(data);
temp->next = head;
head = temp;
}
};
/* Driver code*/
int main()
{
/* Start with the empty list */
LinkedList ll;
[Link](20);
[Link](4);
[Link](15);
[Link](85);

cout << "Given linked list\n";


[Link]();

[Link]();

cout << "\nReversed linked list \n";


[Link]();
return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-7

Q. Write a program to remove duplicates in a singly


linked list.

CODE:
#include <iostream>
using namespace std;

// A linked list class


class LinkedList {
private:
struct Node {
int data;
Node* next;
};
Node* head;

public:
LinkedList() {
head = nullptr;
}

// Utility function to insert a new node at the beginning of the


linked list
void insert(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = head;
head = newNode;
}
// Function to remove duplicates from the linked list
void removeDuplicates() {
Node* current = head;
Node* runner;

// Iterate through the list


while (current != nullptr) {
// Remove all future nodes that have the same value
runner = current;
while (runner->next != nullptr) {
if (runner->next->data == current->data) {
Node* temp = runner->next;
runner->next = runner->next->next;
delete temp;
} else {
runner = runner->next;
}
}
current = current->next;
}
}

// Function to print the linked list


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

// Driver code
int main() {
LinkedList list;
// Inserting elements into the linked list
[Link](10);
[Link](12);
[Link](11);
[Link](11);
[Link](12);
[Link](11);
[Link](10);
cout << "Linked list before removing duplicates: ";
[Link]();

// Removing duplicates
[Link]();

cout << "Linked list after removing duplicates: ";


[Link]();

return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-8

Q. Write a program to convert a binary tree into doubly


linked list.

CODE:

#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
struct ListNode {
int val;
ListNode *prev;
ListNode *next;
ListNode(int x) : val(x), prev(nullptr), next(nullptr) {}
};
class Solution {
public:
ListNode* treeToDoublyList(TreeNode* root) {
if (root == nullptr)
return nullptr;
ListNode* head = nullptr;
ListNode* tail = nullptr;
inOrder(root, head, tail);

// Make the list circular


head->prev = tail;
tail->next = head;
return head;
}

void inOrder(TreeNode* root, ListNode*& head, ListNode*& tail) {


if (root == nullptr)
return;
// Traverse left subtree
inOrder(root->left, head, tail);
// Create a new node for the current element
ListNode* newNode = new ListNode(root->val);
// If head is null, assign newNode to head, otherwise adjust pointers
if (head == nullptr) {
head = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
}
// Update tail to the new node
tail = newNode;

// Traverse right subtree


inOrder(root->right, head, tail);
}
};
// Function to print the doubly linked list
void printList(ListNode* head) {
if (head == nullptr)
return;
ListNode* current = head;
do {
cout << current->val << " ";
current = current->next;
} while (current != head);
cout << endl;
}
int main() {
// Create a binary tree
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(5);
root->right = new TreeNode(15);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(7);
root->right->left = new TreeNode(12);
root->right->right = new TreeNode(20);
// Convert binary tree to doubly linked list
Solution solution;
ListNode* head = [Link](root);

// Print the doubly linked list


cout << "Doubly Linked List: ";
printList(head);

return 0;
}

OUTPUT:

-----------------END------------------
Q. Write a program to check whether the given binary
search tree is balanced or not.

CODE:
#include <iostream>
#include <algorithm>

using namespace std;

// Definition for binary tree node


struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
// Function to check if a binary tree is balanced
bool isBalanced(TreeNode* root) {
// If the tree is empty, it's balanced
if (root == nullptr)
return true;
// Check the height difference between the left and right subtrees
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);

// If the height difference is greater than 1, the tree is unbalanced


if (abs(leftHeight - rightHeight) > 1)
return false;

// Recursively check if left and right subtrees are balanced


return isBalanced(root->left) && isBalanced(root->right);
}
// Function to calculate the height of a binary tree
int getHeight(TreeNode* root) {
if (root == nullptr)
return 0;

// Height of the tree is the maximum height between left and right subtrees + 1
return 1 + max(getHeight(root->left), getHeight(root->right));
}
};
int main() {
// Create a sample binary search tree
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(5);
root->right = new TreeNode(15);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(7);
root->right->right = new TreeNode(20);

// Check if the BST is balanced


Solution solution;
if ([Link](root))
cout << "The binary search tree is balanced." << endl;
else
cout << "The binary search tree is not balanced." << endl;
return 0;
}

OUTPUT:

-----------------END------------------
EXPERIMENT-10

Q. Write a program to traverse a directed graph using


DFS.

CODE:
#include <iostream>
#include <vector>
#include <stack>
#include <unordered_set>

using namespace std;

// Class to represent a directed graph


class Graph {
int V; // Number of vertices
vector<unordered_set<int>> adjList; // Adjacency list

public:
// Constructor
Graph(int vertices) : V(vertices), adjList(vertices) {}

// Function to add an edge to the graph


void addEdge(int u, int v) {
adjList[u].insert(v);
}
// Depth-First Search traversal
void DFS(int startVertex) {
// Vector to keep track of visited vertices
vector<bool> visited(V, false);

// Stack for DFS traversal


stack<int> stack;

// Push the start vertex to the stack


[Link](startVertex);

while (![Link]()) {
// Pop a vertex from stack
int currentVertex = [Link]();
[Link]();
// Process the current vertex if not visited
if (!visited[currentVertex]) {
cout << currentVertex << " ";
visited[currentVertex] = true;

// Push adjacent vertices to the stack


for (int neighbor : adjList[currentVertex]) {
if (!visited[neighbor]) {
[Link](neighbor);
}
}
}
}
}
};
int main() {
// Create a directed graph
Graph graph(6);
[Link](0, 1);
[Link](0, 2);
[Link](1, 3);
[Link](1, 4);
[Link](2, 4);
[Link](3, 5);
[Link](4, 5);

// Perform DFS traversal starting from vertex 0


cout << "DFS traversal starting from vertex 0: ";
[Link](0);

return 0;
}

OUTPUT:

-----------------END-----------------
EXPERIMENT-11
Q. Write a program for quick sort.

CODE:
#include <iostream>
#include <vector>

using namespace std;

// Function to partition the array and return the pivot index


int partition(vector<int>& arr, int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index of smaller element

// Move elements smaller than the pivot to the left of the pivot
for (int j = low; j < high; ++j) {
if (arr[j] < pivot) {
++i;
swap(arr[i], arr[j]);
}
}
// Place the pivot in its correct position
swap(arr[i + 1], arr[high]);

return i + 1; // Return the partitioning index


}

// Function to implement the Quick Sort algorithm


void quickSort(vector<int>& arr, int low, int high) {
if (low < high) {
// Partition the array
int pivotIndex = partition(arr, low, high);

// Recursively sort elements before and after partition


quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}

// Function to print an array


void printArray(const vector<int>& arr) {
for (int num : arr) {
cout << num << " ";
}
cout << endl;
}
int main() {
vector<int> arr = {12, 7, 11, 6, 3, 9};
int n = [Link]();

cout << "Original array: ";


printArray(arr);

// Perform Quick Sort


quickSort(arr, 0, n - 1);

cout << "Sorted array: ";


printArray(arr);

return 0;
}

OUTPUT:

-----------------END-----------------

You might also like