0% found this document useful (0 votes)
13 views18 pages

Lab 06

Uploaded by

f2023065259
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)
13 views18 pages

Lab 06

Uploaded by

f2023065259
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/ 18

University of Management and Technology,

Lahore
Lab Manual: Data Campus
Structures and Algorithm

Lab- 06 Manual
Lab Instructor: Sameer Ahmed
Department of Software Engineering
Email: [email protected]

Array Processing:
Elements of the array are dealt as normal variables, the only difference here is to specify
the index desired. These statements are examples of using array elements:
Lab Manual: Data Structures and Algorithm

16.0 12.0 28.0 26.0 2.5 12.0 14.0 -54.5

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

cout<< x[0]; display the value of x[0], which is 16.0

x[3] = 25.0; stores the value 25.0 in x[3]


sum = x[0] + x[1]; stores the sum of x[0] and x[1], which is 28.0
in the variable sum
x[3] += 1.0; increments x[3] by 1
x[2] = x[0] + x[1]; stores the sum of x[0] and x[1] in x[2]
Now the new x[2] is 28.0
We can apply any expression to specify the index as well. Consider these statements:
i = 5;
cout<< x[i+1]; display 14.0 (value of x[6])
x[i-1] = x[i]; assigns 12.0 (value of x[5]) to x[4]
cout<<x[i++]; display 12.0 (value of x[5])
Invalid index. Attempt to display x[10]

1D dynamic array
#include <iostream>

int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;

// Dynamically allocate memory for a 1D array


int* arr = new int[size];
Lab Manual: Data Structures and Algorithm

// Input elements
std::cout << "Enter " << size << " elements: ";
for(int i = 0; i < size; i++) {
std::cin >> arr[i];
}

// Display elements
std::cout << "Array elements: ";
for(int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;

// Free the allocated memory


delete[] arr;

return 0;
}

Searching in 1D Arrays
#include <iostream>

int linearSearch(int arr[], int size, int key) {


for(int i = 0; i < size; i++) {
if(arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}

int main() {
int size, key;
std::cout << "Enter the size of the array: ";
std::cin >> size;

int* arr = new int[size];


std::cout << "Enter " << size << " elements: ";
for(int i = 0; i < size; i++) {
std::cin >> arr[i];
}

std::cout << "Enter the element to search for: ";


std::cin >> key;
Lab Manual: Data Structures and Algorithm

int result = linearSearch(arr, size, key);


if(result != -1) {
std::cout << "Element found at index: " << result <<
std::endl;
} else {
std::cout << "Element not found" << std::endl;
}

delete[] arr; // Free the allocated memory

return 0;
}

Two Dimensional Arrays


1. Objective:

Learn how to declare, assign and manipulate two dimensions array.


2. Scope:

The student should know the following:


1. What is 2-D array?
2. Declaring 2-D arrays and bound checking.
3. Storing data in 2-D arrays and printing.
4. Passing 2-D arrays to functions.

3. Useful Concepts:

What is 2-D Array?


Just like single dimensional arrays we can have multidimensional arrays which are
arrays of arrays. The multidimensional arrays can be visualized as a matrix.

[0] [1] [2]


[0] 1 2 3
[1] 3 4 5
[2] 6 7 8

General representation of 2-D Array


Lab Manual: Data Structures and Algorithm

How to declare and initialize two multidimensional Array?


int myarray[2][3];
The name of the array to be “myarray”, type of the array elements to be “int”, dimension to be 2 (two
pairs of brackets []). The number of elements or size to be 2*3 = 6.

Array type Array name Array dimensions=2

int myarray[2][3] = {(51, 52, 53),(54, 55, 56)};

Two Rows Three Columns First Row Second Row

We can also write


int b[2][3] = {51, 52, 53, 54, 55, 56};

Or
b[0][0] = 51; b[0][1] = 52; b[0][2] = 53; b[1][0] =
54; b[1][1] = 55; b[1][2] = 56;
or
int b[][3] = {{51, 52, 53}, {54, 55, 56}};

Storing and printing data in 2-D arrays


• A nested for loop is used to input elements in a two dimensional array.
• In this way by increasing the index value of the array the elements can be entered in a 2d
array

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


{ for(int j=0 ; j<3 ; j++)
{ cin<a[i][j];
}
}

• The output of two-dimensional arrays should be in the form of rows and columns for
readability. Nested for loops are used to print the rows and columns in row and column
order.
• By increasing the index value of the array the elements stored at that index value are printed
on the output screen.

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


Lab Manual: Data Structures and Algorithm
{ for(int j=0 ; j<3 ; j++)
{ cout<<a[i][j];
} cout<<endl;
}

Passing 2-D arrays to function:


// Function Call

int array[10][10];
passFunc(array)

;
// Function Definition

void passFunc(int a[][10])


{
// ...

2D dynamic Arrays
#include <iostream>

int main() {
int rows, cols;
std::cout << "Enter the number of rows and columns: ";
std::cin >> rows >> cols;

// Dynamically allocate memory for a 2D array


int** arr = new int*[rows]; // Allocate memory for rows
for(int i = 0; i < rows; i++) {
arr[i] = new int[cols]; // Allocate memory for columns in each row
}

// Input elements
std::cout << "Enter elements for the 2D array: \n";
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
std::cin >> arr[i][j];
}
}
Lab Manual: Data Structures and Algorithm

// Display elements
std::cout << "2D Array elements:\n";
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}

// Free the allocated memory


for(int i = 0; i < rows; i++) {
delete[] arr[i]; // Free each row
}
delete[] arr; // Free the row pointers

return 0;
}

Searching in2D Arrays


#include <iostream>

bool search2DArray(int** arr, int rows, int cols, int key) {


for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(arr[i][j] == key) {
std::cout << "Element found at position: (" << i << ", " << j << ")\n";
return true;
}
}
}
return false;
}

int main() {
int rows, cols, key;
std::cout << "Enter the number of rows and columns: ";
std::cin >> rows >> cols;

int** arr = new int*[rows];


for(int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}

std::cout << "Enter elements for the 2D array: \n";


for(int i = 0; i < rows; i++) {
Lab Manual: Data Structures and Algorithm

for(int j = 0; j < cols; j++) {


std::cin >> arr[i][j];
}
}

std::cout << "Enter the element to search for: ";


std::cin >> key;

if(!search2DArray(arr, rows, cols, key)) {


std::cout << "Element not found\n";
}

// Free the allocated memory


for(int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;

return 0;
}

Linked list:

1. Introduction
Purpose: This lab manual aims to provide an in-depth understanding of singly linked lists, their
structure, and their operations. By completing this lab, students will learn how to implement,
manipulate, and utilize singly linked lists in programming.

2. What is a Linked List


A linked list is a linear data structure that consists of nodes. Each node contains two main
components:

Data: The value or information stored in the node.

Pointer (or Reference): A link to the next node in the sequence.

Unlike arrays, linked lists do not store elements in contiguous memory locations. Instead,
elements (nodes) are linked using pointers, providing flexibility in memory usage and easy
insertion and deletion operations.

3. Why Use Linked Lists


Lab Manual: Data Structures and Algorithm

Dynamic Size: Linked lists can grow or shrink in size as needed, unlike arrays which have a fixed
size.

Ease of Insertion and Deletion: Inserting and deleting nodes in a linked list is more efficient than
in an array, as it does not require shifting elements.

Memory Management: Linked lists allocate memory as needed, which can lead to better
memory utilization.

4. Type of Data Structure


A linked list is a type of linear data structure, where elements are arranged in a linear order. Each
element (node) points to the next, creating a sequence. The most common types of linked lists are:

Singly Linked List: Each node points to the next node.

Doubly Linked List: Each node points to both the next and previous nodes.

Circular Linked List: The last node points back to the head, forming a circular structure.

For this lab manual, we will focus on the singly linked list.

5. Structure of a Singly Linked List


A singly linked list consists of nodes, where each node contains:

Data: The value stored in the node.

Next Pointer: A reference to the next node in the list.

The first node in the list is called the "head." The last node points to null, indicating the end of
the list.
#include <iostream>
using namespace std;

Node Class:

class Node {
public:
int data;
Node* next;

Node(int value) {
Lab Manual: Data Structures and Algorithm

data = value;
next = nullptr;
}
};

Linked list class:

class LinkedList {
private:
Node* head;

public:
LinkedList() {
head = nullptr;
}

// Function to insert a node at the beginning

void insertAtBeginning(int data) {


Node* newNode = new Node(data);
newNode->next = head;
head = newNode;
}

// Function to insert a node at the end


void insertAtEnd(int data) {
Node* newNode = new Node(data);
if (head == nullptr) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
void insertAtIndex(int index, int data) {
Lab Manual: Data Structures and Algorithm

Node* newNode = new Node();


newNode->data = data;
newNode->next = nullptr;

if (index == 0) {
// Insert at the beginning
newNode->next = head;
head = newNode;
} else {
Node* temp = head;
int currentIndex = 0;

// Traverse to the node before the specified index


while (temp != nullptr && currentIndex < index - 1) {
temp = temp->next;
currentIndex++;
}

if (temp != nullptr) {
// Insert at the specified index
newNode->next = temp->next;
temp->next = newNode;
} else {
// Index is out of bounds
std::cout << "Index is out of bounds." << std::endl;
delete newNode;
}
}
}
// Function to delete a node from the beginning

void deleteFromBeginning() {
if (head == nullptr) return;
Node* temp = head;
head = head->next;
delete temp;
Lab Manual: Data Structures and Algorithm

// Function to delete list

void deleteList() {
Node* current = head;
Node* nextNode = nullptr;

while (current != nullptr) {


nextNode = current->next;
delete current;
current = nextNode;
}
head = nullptr;
}

// Function to print the linked list


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

// Destructor to delete the linked list and free memory


~LinkedList() {
Node* current = head;
Node* nextNode = nullptr;
while (current != nullptr) {
nextNode = current->next;
delete current;
current = nextNode;
}
}
};
Lab Manual: Data Structures and Algorithm

int main() {
LinkedList list;

list.insertAtBeginning(3);
list.insertAtBeginning(2);
list.insertAtBeginning(1);

cout << "Linked List after insertAtBeginning operations: ";


list.printList();

list.insertAtEnd(4);
list.insertAtEnd(5);

cout << "Linked List after insertAtEnd operations: ";


list.printList();

list.deleteFromBeginning();
cout << "Linked List after deleteFromBeginning operation: ";
list.printList();

list.deletelist();
cout << "Linked List after deleteFromEnd operation: ";
list.printList();

return 0;
}

Singly circular linked list:

#include <iostream>

class Node {
public:
int data;
Node* next;
Lab Manual: Data Structures and Algorithm

Node(int data) {
this->data = data;
this->next = nullptr;
}
};

class CircularLinkedList {
private:
Node* head;

public:
CircularLinkedList() {
head = nullptr;
}

// Function to add a node at the end (tail) of the list


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

// Function to add a node at the beginning (head) of the list


void insertAtHead(int data) {
Node* newNode = new Node(data);
if (head == nullptr) {
newNode->next = head;
head = newNode;
} else {
Lab Manual: Data Structures and Algorithm

Node* temp = head;


while (temp->next != head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = head;
head = newNode;
}
}

// Function to print the list


void printList() {
if (head == nullptr) {
std::cout << "The list is empty." << std::endl;
return;
}
Node* temp = head;
do {
std::cout << temp->data << " -> ";
temp = temp->next;
} while (temp != head);
std::cout << "(head)" << std::endl;
}

// Function to count the number of nodes


int countNodes() {
if (head == nullptr) return 0;
int count = 0;
Node* temp = head;
do {
count++;
temp = temp->next;
} while (temp != head);
return count;
}

// Function to delete the node at the head


void deleteAtHead() {
Lab Manual: Data Structures and Algorithm

if (head == nullptr) return; // List is empty

if (head->next == head) {
delete head;
head = nullptr;
} else {
Node* temp = head;
while (temp->next != head) {
temp = temp->next;
}
Node* nodeToDelete = head;
head = head->next;
temp->next = head;
delete nodeToDelete;
}
}
};

int main() {
CircularLinkedList list;

list.insertAtTail(10);
list.insertAtTail(20);
list.insertAtTail(30);
list.insertAtHead(5);

std::cout << "List elements: ";


list.printList(); // Output: 5 -> 10 -> 20 -> 30 -> (head)

std::cout << "Total nodes: " << list.countNodes() << std::endl; // Output: Total
nodes: 4

list.deleteAtHead();
std::cout << "List elements after deleting head: ";
list.printList(); // Output: 10 -> 20 -> 30 -> (head)

return 0;
}
Lab Manual: Data Structures and Algorithm

Task 1: Delete from the Beginning


Implement a function to delete a node from the beginning of a singly linked list.

Instructions:

Define a Node class with data and next pointer.

Create a LinkedList class with a head pointer.

Implement the deleteFromBeginning function in the LinkedList class.

Add nodes to the linked list, delete a node from the beginning, and print the list to verify.

Task 2: Delete the Entire List


Implement a function to delete the entire singly linked list and free all allocated memory.

Instructions:

Define a Node class with data and next pointer.

Create a LinkedList class with a head pointer.

Implement the deleteList function in the LinkedList class.

Add nodes to the linked list, delete the entire list, and verify that the list is empty.

Task 3: Insert at Specific Position

Implement a function to insert a node at a specific position in a singly linked list.

Instructions:

1. Define a Node class with data and a next pointer.


2. Create a LinkedList class with a head pointer.
3. Implement the insertAtPosition function in the LinkedList class.
4. Add nodes to the linked list at specific positions and verify the list structure.

Task 4: Insert at Head

Implement a function to insert a node at the head (beginning) of a singly circular linked list.
Lab Manual: Data Structures and Algorithm

Instructions:

1. Define a Node class with data and a next pointer.


2. Create a CircularLinkedList class with a head pointer.
3. Implement the insertAtHead function in the CircularLinkedList class.
4. Add nodes to the list at the head position and verify the list structure.

Task 5: Insert at Tail

Objective: Implement a function to insert a node at the tail (end) of a singly circular linked list.

Instructions:

1. Define a Node class with data and a next pointer.


2. Create a CircularLinkedList class with a head pointer.
3. Implement the insertAtTail function in the CircularLinkedList class.
4. Add nodes to the list at the tail position and verify the list structure.

Task 6: Delete at Head

Objective: Implement a function to delete the node at the head of a singly circular linked list.

Instructions:

1. Define a Node class with data and a next pointer.


2. Create a CircularLinkedList class with a head pointer.
3. Implement the deleteAtHead function in the CircularLinkedList class.
4. Add and delete nodes from the head position, and verify the list structure.

Task 7: Count Number of Nodes

Objective: Implement a function to count the number of nodes in a singly circular linked list.

Instructions:

1. Define a Node class with data and a next pointer.


2. Create a CircularLinkedList class with a head pointer.
3. Implement the countNodes function in the CircularLinkedList class.
4. Add nodes to the list, count the nodes, and verify the count.

You might also like