DSA Lab Manual Noman
DSA Lab Manual Noman
Submitted By:
Name: Noman Bin Saeed
CMS ID: 57447
Department of Information Technology
1
Table of Contents:
General Format of each Lab ......................................................................................................................... 3
Lab Task 01 – Structures, Classes, and Arrays ............................................................................................. 4
Lab # 2 : This lab covers the concepts linked list. ........................................................................................ 7
Question 01: Create a program where user can create a Linked List by adding Nodes to the Tail of the
Linked list instead of the Head. ................................................................................................................ 7
Question 02: Create program where user can create a Linked List by deleting the Nodes from the Tail
of the Linked list instead of the Head....................................................................................................... 9
Lab Task 03 – Single Linked Lists ............................................................................................................. 13
Lab Task 04 – Doubly Linked Lists............................................................................................................ 16
Lab Task 05 – Basics of Stack .................................................................................................................... 21
Lab Task 06 – Applications of Stack: Expression Matching ...................................................................... 25
Lab Task 07 – Stack Applications: Infix to Postfix .................................................................................... 28
Lab Task 08 – Implementation of Queues using Stacks ............................................................................. 29
Lab Task 09 – Implementation of Bubble Sort and Selection Sort............................................................ 31
Lab Task 10 – Depth First Traversal of a Binary Tree ............................................................................... 32
2
General Format of each Lab
Question: First, copy the given lab and write down all the questions given in the lab.
Tools: Write down the tool you used to complete the lab. (Written once for the complete lab)
Procedure: (Written for each question in the lab)
1. Write down the steps you followed to achieve each question.
2. This procedure should be repeated for each question in the lab.
3. Also, the procedure should be written in bullets.
4. Sample is given in the figure below.
Code: (Written for each question in the lab)
1. Write down the code you developed for this lab.
2. Also, attach the screenshots of the running program.
3. The sample is just for Question 01 of the lab.
4. You have to complete it for all questions of the lab.
5. New lab should always start from the new page.
6. Your lab should also consist of the “Table of Contents”
3
Lab Task 01 – Structures, Classes, and Arrays
Question 01:
Create a program consisting of a struct that contains record of the user. Attributes of the structure should
be:
• First Name
• Last Name
• CNIC
• Height
• Field1
• Field2
• Field3
Create an array object of the structure consisting of 5 elements. Add values to these elements and display
In this lab I have seen the use of structures , how to nest a structure and making object array of that
structures along with that to use functions to in objects and array of objects. The struct record and cnic
stores the data of various users and in main function we create object of five structures which asks the
user to enter the data of five users. We ask the user number of objects he wants to create because we
iterate loop till there . finally, we display the each object accessing its properties.
Procedure:
1.First I define a structure CNIC which has three attributes field1, field2,field3.
2. then I define another structures of user records to store first name , last name and height of the user.
4. Ask the user how many objects he want to create , so we will execute loop till there .
4. then program asks the user to enter the data (fist name , last name, height, and three fields of cnic ).
4
5.then it simply displays the information using for loop.
Code:
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
struct CNIC {
string field1;
string field2;
string field3;
};
struct UserRecord {
string firstName;
string lastName;
CNIC cnic;
double height;
};
int main() {
int siz;
UserRecord users[5];
}
cout << " Enter the number of objects " << endl;
cin >> siz;
for (int i = 0; i <siz ; i++) {
cout << " user " << i + 1 << endl;
cout << "Name:" << endl;
cin >> users[i].firstName;
cout << " Last name:" << endl;
cin >> users[i].lastName;
cout << "height:" << endl;
cin >> users[i].height;
cout << " CNIC :" << endl;
cin >> users[i].cnic.field1 >> users[i].cnic.field2
>>users[i].cnic.field3;
}
// Displaying the user records
for (int i = 0; i < siz; ++i) {
cout << "User " << i + 1 << ":\n";
cout << "First Name: " << users[i].firstName << "\n";
cout << "Last Name: " << users[i].lastName << "\n";
cout << "CNIC: " << users[i].cnic.field1 << "-" << users[i].cnic.field2
<< "-" << users[i].cnic.field3 << "\n";
cout << "Height: " << users[i].height << " cm\n";
cout << "--------------------------\n";
}
5
return 0;
}
Output:
6
Lab # 2 : This lab covers the concepts linked list.
Question 01: Create a program where user can create a Linked List by adding
Nodes to the Tail of the Linked list instead of the Head.
Procedure:
• First I defined the Node class
• Then the Linked list class
• Define add to Tail function , with certain conditions
• Display function to show the values of list
• Then initializes instance of the linked list called lilnkedlist.
• Used a do-while loop the repeatedly prompts the uer for a value and ask whether they want
to add another value.
• Finally calls add to tail function to add the entered value to the linked list.
Code:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
7
LinkedList(Node* head=NULL) {
head = head;
}
void addToTail(int value) {// function to append at tail
Node* newNode = new Node(value);
if (!head) {
head = newNode;
}
else {
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
void display() {
Node* current = head;
while (current) {
std::cout << current->data << " -> ";
current = current->next;
}
cout << "nullptr" << endl;
}
};
int main() {
LinkedList linkedList;
//LinkedList linkedList;
char addAnother;
do {
int value;
cout << "Enter the value: ";
cin >> value;
cout << endl;
linkedList.addToTail(value);
return 0;
}
Output:
8
Question 02: Create program where user can create a Linked List by deleting the
Nodes from the Tail of the Linked list instead of the Head.
Procedure:
• First I defined the Node class
• Then the Linked list class
• Define Delete to Tail function , with certain scenarios.
• Display function to show the values of list
• Then initializes instance of the linked list called lilnkedlist.
• Used a do-while loop the repeatedly prompts the user for a value and ask whether they
want to add another value.
• Finally calls add to tail function to add the entered value to the linked list.
9
Code:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
}
void addToTail(int value) {// function to append at tail
Node* newNode = new Node(value);
if (!head) {
head = newNode;
}
else {
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
void display() {
Node* current = head;
while (current) {
cout << current->data << " -> ";
current = current->next;
}
cout << "nullptr" << endl;
}
void deleteFromTail() {
if (!head) {
std::cout << "The linked list is empty" << endl;
return;
}
if (!head->next) {
// If there is only one node in the list, delete it
delete head;
head = NULL;
return;
}
10
Node* current = head;
Node* previous = nullptr;
int main() {
LinkedList linkedList;
//LinkedList linkedList;
char addAnother;
do {
int value;
cout << "Enter the value: ";
cin >> value;
cout << endl;
linkedList.addToTail(value);
Final outputs:
11
12
Lab Task 03 – Single Linked Lists
Question 01 Create
a program where user can create Single Linked List by adding
Nodes. The nodes should be added in ascending order at the time of inserting a new
Node. Implement a main() function of the questions
Understanding of the Lab:
In this lab explored the concept of linked list more .In this program , the linked list class contains
a member function ‘insertNode’ which inserts a new node in to the list while maintaining the
ascending order. Such that the smaller values comes at first and then greater and so on. The display
function is used to display the linked list.
In main function the instance of linked list class is created and values are provided to the functions.
Procedure:
• First I defined the Node class
• Then the Linked list class
• Define insert node function , that should insert the values in the linked list in ascending
order.
• Display function to show the values of list
• Then initializes instance of the linked list called lilnkedlist.
• Used a do-while loop the repeatedly prompts the user for a value and ask whether they
want to add another value.
• Finally called the inset node function after entering the values in to the linked list.
Code:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
13
void insertNode(int value) {
Node* newNode = new Node(value);
// If the list is empty or the new node should be the first node
if (head == nullptr || value < head->data) {
newNode->next = head;
head = newNode;
}
else {
Node* current = head;
// Traverse the list to find the correct position for the new node
while (current->next != nullptr && current->next->data < value) {
current = current->next;
}
int main() {
LinkedList linkedList;
//LinkedList linkedList;
char addAnother;
do {
int value;
cout << "Enter the value: ";
cin >> value;
cout << endl;
linkedList.insertNode(value);
cout << "Add another (Y/N)? ";
cin >> addAnother;
linkedList.displayList();
cout << endl;
return 0;
}
14
Final outputs:
15
Lab Task 04 – Doubly Linked Lists
Question 01: Create a program where user can create Doubly Linked List by adding Nodes to the Head
of the linkedlist. You can implement the mechanism in the addToHead(int element) method.
Question 02: Create a program where user can delete a Node(s) from the Head of the Linked List. You
can implement the mechanism in the deleteFromHead() method.
Code:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node* prev;
16
};
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList( ) {
head = NULL;
}
void addToHead(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
}
else {
// Otherwise, adjust pointers to make the new node the head
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}
void displayList() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
void deleteFromHead() {
if (head == nullptr) {
std::cout << "List is empty. Cannot delete from head.\n";
return;
}
if (head->next==NULL) {
// If there's only one node in the list
head = nullptr;
}
else {
// Otherwise, adjust pointers to remove the node from the head
head = head->next;
head->prev = nullptr;
}
delete temp;
}
};
int main() {
DoublyLinkedList linkedList;
17
do {
cout << " 1: for add to head:" << endl;
cout << " 2: Delete from head:" << endl;
cout << " 3: Display the linked list:" << endl;
switch (val)
{
case 1:
cout << "Enter the value: ";
cin >> value;
cout << endl;
linkedList.addToHead(value);
break;
case 2:
linkedList.deleteFromHead();
break;
case 3:
linkedList.displayList();
break;
case 4:
exit(0);
default:
cout << " Enter a valid option:";
break;
}
} while (val!=4 );
return 0;
}
Final outputs:
Adding to head of the linked list.
18
Deleting from the head of the linked list.
19
20
Lab Task 05 – Basics of Stack
Question 1: Create a program implementing a Stack using Single linked list.
In this lab I have seen how to use stack using linked list to push and pop elements from the stack and
display the contents of the stack. Here character structure is defined which represents single element of
the stack ‘ char’ and a pointer next to the next character node in the stack. A parametrized constructer
initialize the value given and next is pointing to the NULL;
Procedure:
1.push(character*& head, int value), which pushes a character on to the stack it creates a new
character node with the provided value ‘Val’ and updates the ‘next’ pointer of the new node to
point to the current ‘head’ .
2. pop the pop function (removes ) a character from the top of the stack and checks if stack is
empty by the head pointer if it is not empty it updates the head to point to the next node and the
deletes the memory.
3.Display , this functions displays the contents of the stack it issues temporary pointer to traverse
stack while printing data of each element.
4. isEmpty , this functions checks if the stack is empty by examining the head pointer.
1. In main function, a loop allows the user to interact with the stack through a menu-driven
interface, user can check elements , displays , pop and dynamically allocates memory for
new nodes when pushing elements onto the stack.
Code:
#include <iostream>
using namespace std;
21
char data;
Character* next;
Character(char val) {
data = val;
next = NULL;
}
};
int main() {
Character* head = NULL;
char choice;
do {
int option;
cout << "Do you want to run the program? (y/n): ";
cin >> choice;
cout << "\tMenu:" << endl;
cout << "1: Push onto the stack" << endl;
cout << "2: Pop from the stack" << endl;
cout << "3: Display stack contents" << endl;
cout << "4: Check if stack is empty" << endl;
cout << "5: Exit" << endl;
cin >> option;
22
switch (option) {
case 1:
char value;
cout << "Enter the value: ";
cin >> value;
push(head, value);
break;
case 2:
cout << "After popping the element:" << endl;
pop(head);
break;
case 3:
cout << "The elements of the stack are: ";
display(head);
break;
case 4:
if (isEmpty(head)) {
cout << "Stack is empty." << endl;
}
else {
cout << "Stack is not empty." << endl;
}
break;
case 5:
exit(0);
break;
default:
cout << "Please enter a valid option." << endl;
break;
}
} while (choice != 'n' && choice != 'N');
return 0;
}
Output:
23
Now to pop (removes ) from stack and display it.
As you see in above picture after popping we get only four element which was the last
element but now it is the first.
24
Lab Task 06 – Applications of Stack: Expression Matching
Question 1: Create a program implementing a Stack using Single Linked List for the following Node:
Implement the functionalities of following methods:
void push(char);
char pop();
bool isEmpty();
Implement a checkExpression() function which should take any Expression String as input and returns
aBoolean value indicating whether the entered Expression String is balanced or not
Procedure:
1.push(character*& head, int value), which pushes a character on to the stack it creates a new
character node with the provided value ‘Val’ and updates the ‘next’ pointer of the new node to
point to the current ‘head’ .
2. pop the pop function (removes ) a character from the top of the stack and checks if stack is
empty by the head pointer if it is not empty it updates the head to point to the next node and the
deletes the memory.
3.Display , this functions displays the contents of the stack it issues temporary pointer to traverse
stack while printing data of each element.
4. isEmpty , this functions checks if the stack is empty by examining the head pointer.
1. In main function, a loop allows the user to interact with the stack through a menu-driven
interface, user can check elements , displays , pop and dynamically allocates memory for
new nodes when pushing elements onto the stack.
Code:
#include <iostream>
#include<string.h>
using namespace std;
25
struct Character {
char ch;
Character* next;
class CharStack {
private:
Character* top;
public:
CharStack() {
top = NULL;
}
return poppedChar;
}
bool isEmpty() {
return top == nullptr;
}
};
26
char poppedChar = charStack.pop();
if ((c == ')' && poppedChar != '(') ||
(c == ']' && poppedChar != '[') ||
(c == '}' && poppedChar != '{')) {
return false; // Mismatched opening and closing brackets
}
}
}
int main() {
string expression;
cout << "Enter an expression: ";
cin>> expression;
27
Lab Task 07 – Stack Applications: Infix to Postfix
28
Lab Task 08 – Implementation of Queues using Stacks
29
Lab Task 09- Recursion
30
Lab Task 10 – Implementation of Bubble Sort and Selection Sort
31
Lab Task 10 – Depth First Traversal of a Binary Tree
Question no 1:
Create a program where user can display the values of a nodes present in a
binary search tree . The nodes of this binary tree must comprise of characters
initially you will have to insert the values to a tree . Next step is to traverse this
tree using
Pre Order Traversal
Post Order traversal
In Order traversal
In this lab I have learned how to traverse the whole tree with help of some traversal
methods. In order, preorders and post order traversal . Each of it adapts different
methods for traversal but with common functionality of visiting each node of the
tree.
Inorder traversal : in this traversal we first visit the left node of the tree then data
and at last the right node is accessed.
Preoder traversal :
In this traversal first data of each node is accessed then left node after that at last
right node is printed.
postorder traversal In post order we visit first the left pointer then right pointer
and at last we visit the data of the node. Examples of traversal is shown below.
Procedure :
• First created node class and BST traversal class along with declaration of
inorder , preorder and post order traversal in public part of BST class.
• Insert the nodes in BST .
• In pre order if tree not empty we print data, move left and then right.
• In inorder if tree is not empty we first move to left , data and then right.
• In post order if the tree is not empty then we move first left , right and then
print data.
32
• Finally in main function we call traversal functions to execute its
functionalities.
Code :
// lab11_traversals.cpp : This file contains the 'main' function. Program execution
begins and ends there.
#include <iostream>
using namespace std;
class node {
public:
char data;
node* left;
node* right;
};
class BSTtraversal {
public:
node* root;
BSTtraversal(node* ro=NULL) {
root = ro;
}
preorder(root->left);
preorder(root->right);
return;
}
}
void inorder(node* root) {
if (root == NULL) {
return;
}
else {
inorder(root->left);
cout << " " << root->data;
inorder(root->right);
return;
}
}
33
void postorder(node* root)
{
if (root == NULL) {
return;
}
else {
postorder(root->left);
postorder(root->right);
return;
}
}
void insert(node* root, char key) {
node* New = new node(key);
node* pre= new node(key);
else
insert(root->left, key);
}
if(pre->data>key){
pre->right = New;
}
else {
pre->left = New;
}
return;
}
};
int main()
{
BSTtraversal ro;
int choice;
char vale;
node* p = new node('m');
node* p1 = new node('s');
node* p2 = new node('a');
node* p3 = new node('l');
node* p4 = new node('e');
node* p5 = new node('k');
node* p6 = new node('p');
34
p->left = p2;
p2->right = p4;
p->right = p1;
p1->left = p3;
p1->left = p6;
p6->left = p3;
do {
cout << endl;
cout << " 1: for inorder traversal:" << endl;
cout << " 2: for preorder traversal:" << endl;
cout << " 3: for postorder traversal:" << endl;
cout << " 4: Exit:" << endl;
cin >> choice;
switch (choice)
{
case 1:
ro.inorder(p);
cout << endl;
break;
case 2:
ro.preorder(p);
break;
case 3:
ro.postorder(p);
break;
case 4:
exit(0);
break;
}
} while (choice != 4);
return 0;
}
Output:
35
36