0% found this document useful (0 votes)
12 views47 pages

Dsa Lab Manual Actual

Uploaded by

alina.raza2017
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)
12 views47 pages

Dsa Lab Manual Actual

Uploaded by

alina.raza2017
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/ 47

DATA STRUCTURS & Lab Manual

ALGORITHMS
Lab 01
Programming with C++
Objective:

In this lab, students will get familiar with the C++ language, with the help of simple programs that will
provide handson training to learn the syntax of the language. Beside learning the basics of C++ like control
statements, functions, arrays, etc., you will also learn the concept of Array

Activity Outcomes:

The activities provide hands - on practice with the following topics

 Usage of input / output statements in C++


 Usage of different datatypes
 Implement Control Statements
 Modularity using Functions

Instructor Note:

As a pre-lab activity, read fundamental concepts from the text book “C++ How to Program,
Deitel, P. & Deitel, H., Prentice Hall, 2019”.”.
1) Useful Concepts
C++, as we all know is an extension to C language and was developed by Bjarne stroustrup at bell labs.
C++ is an intermediate level language, as it comprises a confirmation of both high level and low level
language features.

Following features of C++ makes it a stronger language than C,


1. There is Stronger Type Checking in C++.
2. C++ supports and allows user defined operators (i.e Operator Overloading) and function
overloading is also supported in it.
3. Exception Handling is there in C++.
4. Inline Functions in C++ instead of Macros in C language. Inline functions make complete
function body act like Macro, safely.
5. Variables can be declared anywhere in the program in C++, but must be declared before they are
used.
2) Installing GNU C/C++ Compiler
Install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage,
www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the
MinGW installation program which should be named MinGW-<version>.exe.

While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW
runtime, but you may wish to install more.

Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can
specify these tools on the command line by their simple names.

When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other
GNU tools from the Windows command line.

3) IDE for coding


The IDE we will be using is Dev-C++. Today we will clear our concepts regarding the syntax of C++ with
the help of small programs.

Note: we use cin for input and cout for output/print.

At start of your program always use


4) Solved Lab Activites
Sr.No Allocated Time Level of Complexity CLO Mapping
1 5 Mins Low CLO-4
2 5 Mins Low CLO-4
3 5 Mins Low CLO-4
4 5 Mins Low CLO-4
5 5 Mins Low CLO-4
6 5 Mins Low CLO-4
7 5 Mins Low CLO-4
8 5 Mins Low CLO-4
9 15 Mins Medium CLO-4
10 5 Mins Low CLO-4
11 5 Mins Low CLO-4
12 10 Mins Low CLO-4
13 5 Mins Low CLO-4

Activity 1:
Simple Program to print welcome on screen. It also uses Single Line, Multi Line comments and basic
Output in C++.

Solution:
// Our First Program
/* Multiple line
* comment
*/

#include<iostream>

using namespace std;

int main()
{
cout<<"Welcome to CS211 DSA Lab";
return 0;
}
Output
Welcome to CS211 DSA Lab
Activity 2:
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded by double quotes
 bool - stores values with two states: true or false

#include <iostream>
using namespace std;
int main () {
float a=5.5; // initial value: 5
int b(3); // initial value: 3
int c{2}; // initial value: 2
float result; // initial value undetermined
a = a + b;
result = a – c
cout << “Result is “<< result;
return 0;
}

Output
Result is 6.5
Activity 3:
Input values using cin statement.

#include <iostream>
using namespace std;
int main () {
int a, b, c, result; // multiple variable declaration
cout << ”Enter value for variable a ?” ;
cin >> a;
cout << ”Enter value for variable b ?” ;
cin >> b;
cout << ”Enter value for variable c ?” ;
cin >> c;
result = a + b + c ;
cout << “Result is “<< result;
return 0;
}

Output
Enter value for variable a ? 5

Enter value for variable b ? 4

Enter value for variable c ? 3

Result is 12

Activity 4:
Using Arithematic Operators

Operator Name Description Example


+ Addition Adds together two values x+y
- Subtraction Subtracts one value from x-y
another
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division x%y
remainder

#include <iostream>
using namespace std;
int main () {
int a, b, c, result; // multiple variable declaration
a = 40;
b = 23;
c = 15;
result = (a - b + c) / 4 ;
cout << “Result is “<< result;
return 0;
}

Output
Result is 8

Activity 5:
𝒃𝟐 𝟒𝒂𝒄
Using Arithematic Operator; how do we write
𝟐𝒂

#include <iostream>
using namespace std;
int main () {
int a, b, c, result; // multiple variable declaration
a = 10;
b = 25;
c = 5;
result = (b*b – 4*a*c) / (2*a) ; // there is no power operator
cout << “Result is “<< result;
return 0;
}
Output
Result is 21.25
Activity 6:
Using Arithematic (increment / decrement) Operator;

Operator Name Description Example


++ Increment Increases the value of a ++x
variable by 1
-- Decrement Decreases the value of a --x
variable by 1

#include <iostream>
using namespace std;
int main () {
int a, b, c, d;
a = 10;
b = 15;
c = a++;
d = ++a;
e = b--;
f = --b;
cout << “\n a is “<< a
<< “\n b is “<< b
<< “\n c is “<< c
<< “\n d is “<< d
<< “\n e is “<< e
<< “\n f is “<< f << endl;
return 0;
}

Output
a is 12
b is 13
c is 10
d is 12
e is 15
f is 13

Activity 7:
Using Conditional Operator;

#include <iostream>
using namespace std;
int main () {
int a, b, c;
a = 10;
b = 25;
c = (a>b) ? a : b;
cout << “Large number is “<< c;
return 0;
}

Output
Large number is 25

Activity 8:
Determining a number is even or odd using if statement;

#include <iostream>
using namespace std;
int main () {
int a;
cout << “Enter any integer “ ;
cin >> a;
if (a%2==0)
cout << a << “ is an even number”;
else
cout << a << “ is an odd number”;
return 0;
}

Output
Enter any integer 46

46 is an even number

Activity 9:
Write a program to compute need based scholarship for a student if GPA and parent’s income is
provided according to the following table.

Parents’s Income GPA 4.0 3.0 ~ 3.9 2.5 ~ 3.0 Below 2.5
Below Rs 100,000 FULL HALF QUARTER N/A
100,000 to 150,000 HALF QUARTER N/A N/A
150,000 to 200,000 QUARTER N/A N/A N/A
Above 200,000 N/A N/A N/A N/A
Note: Use nested if statement to find out scholarship type.
#include <iostream>
using namespace std;
int main() {
long income;
float gpa;
// Input income and gpa
cout << "Enter your parent\’s income: ";
cin >> income;
cout << "Enter your gpa : ";
cin >> gpa;
// Nested if statements to determine scholarship type
if (gpa == 4.0)
if (income <= 100000)
cout << "You qualified for full scholarship";
else if (income > 100000 && income <= 150000)
cout << "You qualified for half scholarship";
else if (income > 150000 && income <= 200000)
cout << "You qualified for half scholarship";
else
cout << "not qualified for any scholarship";
else if (gpa < 4.0 && gpa >= 3.0)
if (income <= 100000)
cout << "You qualified for half scholarship";
else if (income > 100000 && income <= 150000)
cout << "You qualified for quarter scholarship";
else
cout << "not qualified for any scholarship";
else if (gpa < 3.0 && gpa >= 2.5)
if (income <= 100000)
cout << "You qualified for quarter scholarship";
else
cout << "not qualified for any scholarship";
else
cout << "not qualified for any scholarship";
}

Activity 10:
Write a program to read in a value from 1 to 4, and use switch statement to check and displays
according to the following table.

Input Display
1 Hello
2 Goodbye
3 Welcome
4 Exit

#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Menu:\n";
cout << "1. Print Hello\n";
cout << "2. Print Goodbye\n";
cout << "3. Print Welcome\n";
cout << "4. Exit\n";
cout << "Enter your choice (1-4): ";
cin >> choice;
switch (choice) {
case 1:
cout << "Hello!\n"; break;
case 2:
cout << "Goodbye!\n"; break;
case 3:
cout << "Welcome!\n"; break;
case 4:
cout << "Exiting program...\n"; break;
default:
cout << "Invalid choice. Please enter a number
between 1 and 4.\n"; break;
}
return 0;
}

Activity 11:
Write a program to sum first 10 numbers starting from 1, using for loop;

#include <iostream>
using namespace std;
int main() {
int sum = 0;
// For loop to sum numbers from 1 to 10
for (int i = 1; i <= 10; ++i) {
sum += i;
}
cout << "Sum of numbers from 1 to 10 is: " << sum << endl;
return 0;
}

Activity 12:
Using while loop statement, write a program to display the following sequence’s first 20 terms;

1, 5, 9, …
#include <iostream>
using namespace std;
int main() {
int t, a=1, d=4,c=1;
do {
cout << t <<”, “;
t = a + d*c;
c++;
} while (c<20)
return 0;
}

Activity 13:
Write a program that will add two numbers in a function and call that function in main.
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
5) Graded Lab Tasks
Note: The instructor can design graded lab activities according to the level of difficulty and
complexity of the solved lab activities. The lab tasks assigned by the instructor should be
evaluated in the same lab.
Lab Task 1
Write a function that takes an integer and then returns the number with the digits reversed. For example,
if the input is 12345, the output should be 54321.

int reverseInteger(int value)

Lab Task 2
Write a function that takes two integers as input and returns the largest from these two input numbers.

int maximum(int a, int b)




}

Lab Task 3
Write a function which takes an integer argument value and displays the weekday corresponding to that
number. E.g. 1 for Monday, 2 for Tuesday,… 7 for Sunday, on any other number it should print wrong
input is provided.

Input: 3

Output: Wednesday

Lab Task 4
Use for loop to print this diamond shape.
*
**
***
****
*****
****
***
**
*

Lab Task 5
Marks of a student in five different subjects are given as following

[90,60,80,50,60]
Write a program to calculate average, and overall grade according to this criteria:
Marks Grade.
85% and above A
70% to 84% B
60% to 69% C
50% to 59% D
Below 50% F
Note: use user-defined functions,
Lab 2
Static List

Objective:

In this lab, students will learn how to create, manuplate and display one dimension arrays. How arrays can
be passed to functions and how arrays can be returned. They will also get familiarize with structures &
arrays of structures. Student will also do hands-on practice to make ArrayList using integer array and static
linked list.

Activity Outcomes:

The activities provide hands - on practice with the following topics

 Array Declaration and Initialization


 Array Traversal – input and output
 Passing Arrays to a Function and returning Array from function
 Creating ArrayList and related functions
 Creating StaticLinkedList and functions to manage

Instructor Note:

As a pre-lab activity, read fundamental concepts from the text book “C++ How to Program,
Deitel, P. & Deitel, H., Prentice Hall, 2019”.”.
6) Useful Concepts
In C++, an array is a collection of elements of the same type placed in contiguous memory locations.
Arrays provide a way to store multiple values in a single variable, which can be accessed using indices.
Here’s a detailed overview of arrays in C++:

Declaration and Initialization

To declare an array, you specify the type of its elements and the number of elements it can hold. For
example:

int arr[5]; // Declares an array of 5 integers

You can also initialize the array at the time of declaration:

int arr[5] = {1, 2, 3, 4, 5}; // Array of 5 integers initialized


with values

If you don't specify the size, it is inferred from the number of initializers:

int arr[] = {1, 2, 3, 4, 5}; // Size is automatically 5

Accessing Elements:

Array elements are accessed using an index, with indices starting from 0. For example:

int firstElement = arr[0]; // Accesses the first element

int thirdElement = arr[2]; // Accesses the third element

Size and Iteration:

You can determine the size of an array using the `sizeof` operator. For example:

int size = sizeof(arr) / sizeof(arr[0]); // Calculates the number of


elements in the array

You can iterate through an array using a loop:

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


cout << arr[i] << " ";

Characteristics of Arrays

1. Fixed Size:
The size of an array is fixed at compile time. This means once you declare an array, its size
cannot be changed during runtime.

2. Contiguous Memory:
Arrays allocate memory for all their elements in a contiguous block, which allows for efficient
access and iteration.
3. Zero-Based Indexing:
Array indices start at 0. For an array of size `n`, valid indices range from `0` to `n-1`.

4. Multidimensional Arrays:
C++ supports multidimensional arrays, such as two-dimensional arrays (matrices). For example:

int matrix[3][4]; // A 2D array with 3 rows and 4 columns

int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
// Initialization

7) Solved Lab Activites


Sr.No Allocated Time Level of Complexity CLO Mapping
1 5 Mins Low CLO-4
2 5 Mins Low CLO-4
3 5 Mins Low CLO-4
4 5 Mins Medium CLO-4
5 10 Mins Low CLO-4
6 15 Mins Medium CLO-4
7 10 Mins Medium CLO-4
8 20 Mins Medium CLO-4
Activity 1:
Use of Arrays – array declaration, initialization, and traversal.

Solution:
// Our First Program
/* Multiple line
* comment */

#include<iostream>

using namespace std;

int main() {
int A[5]={3,4,6,7,8};
for (int i=0; i<5;i++)
cout<<A[i] << “,”;
return 0;
}
Output
3, 4, 6, 7, 8

Activity 2:
Write a function to display contents of an array.

#include <iostream>
using namespace std;
void display(int A[], int size) {
for (int i=0;i<size;i++) cout << A[i];
}
int main () {
int A[5]={3,4,6,7,8};
display(A,5);
return 0;
}

Output
3, 4, 6, 7, 8

Activity 3:
Write a function which will exchange two elements of an array.

#include <iostream>
using namespace std;
void swap(int A[], int i,int j) // A[i]  A[j]
{
int t=A[i];
A[i]=A[j];
A[j]=t;
}
void display(int A[], int size) {
for (int i=0;i<size;i++) cout << A[i];
}
int main () {
int A[5]={3,4,6,7,8};
display(A,5);
swap(A,2,4);
display(A,5);
return 0;
}

Output
3, 4, 6, 7, 8

3, 4, 8, 7, 6

Activity 4:
Creating an arraylist using simple integer array, and write functions to insert and display elements.

#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
int A[MAX_SIZE];
int position=0; // where the first value be inserted

void insert(int A[], int value) {


if (position<MAX_SIZE)
A[position++] = value;
}

void display(int A[]) {


for (int i=0;i<position;i++) cout << A[i];
}
int main () {
insert(A, 3);
insert(A, 4);
insert(A, 6);
insert(A, 7);
insert(A, 8)
display(A);
return 0;
}

Output
3, 4, 6, 7, 8

Activity 5:
Write a function to delete an element from ArrayList.

#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
int position=0; // where the first value to be inserted
void insert(int A[], int value) {
if (position<MAX_SIZE)
A[position++] = value;
}
void remove(int A[], index i) // remove the value from i index
{
if (i<position) {
for (int j=i; j<position;j++)
A[j]=A[j+1];
position--;
}
}

void display(int A[]) {


for (int i=0;i<position;i++) cout << A[i];
}
int main () {
insert(A, 33);
insert(A, 44);
insert(A, 56);
insert(A, 67);
insert(A, 78);
remove(A, 3);
display(A);
return 0;
}

Output
33, 44, 56, 78

Activity 6:
Suppose we have two ArrayLists let say A and B, how do we can create two lists using above code.

The answer is to create two arrays, two MAX_SIZE variables and two position variables, such as

int A[MAX_SIZE_A], int B[MAX_SIZE_B] etc.

In above example, we created an array to store values, a maximum variable which stores how many
values can be stored, and the third variable position to keep track of the position in array where next
value will be inserted.

To group these items together we need to use either classes or structures; As per our course
requirement we will use the structures to group things together.

To define composite types we use structures, one of the common examples of composite types is date,
where three integers make up a date structure;

#include <iostream>
using namespace std;

const int MAX_SIZE = 10;


struct ArrayList
{
int Element[MAX_SIZE];
int position=0;
};

void insert(ArrayList *List, int value) {


if (List->position<MAX_SIZE)
List->Element[List->position++] = value;
}
void remove(ArrayList *List, int index) {
if (index<List->position) {
for (int j=index; j<List->position;j++)
List->Element[j]=List->Element[j+1];
List->position--;
}
}
void display(ArrayList *List) {
for (int i=0;i<List->position;i++)
cout << List->Element[i];
}
int main () {
ArrayList A, B;
insert(&A, 3);
insert(&A, 5);
insert(&B, 6);
insert(&B, 8);
display(&A);
display(&B);
return 0;
}

Output:

3, 5

6, 8

Activity 7:
In previous two activites we used remove function, which removes the content of ith position value
with the next (i+1)th value, and respectively all the value upto last element are shifted one step
backward.

This approach is considered slow – ie. If we remove first element from list we need to shift rest of the
list. To tackle this issue and to make list more effienct we can simple mark that element as any –ve
number so that can be considered as deleted.

#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
struct ArrayList
{
int Element[MAX_SIZE];
int position=0;
};

void insert(ArrayList *List, int value) {


if (List->position<MAX_SIZE)
List->Element[List->position++] = value;
}
void remove(ArrayList *List, int index) {
if (index<List->position) {
List->Element[j]= -9999; // this is considered deleted
}
}
void display(ArrayList *List) {
for (int i=0;i<List->position;i++)
if (List->Element[i]!=-9999)
cout << List->Element[i];
}
int main () {
ArrayList A, B;
insert(&A, 3);
insert(&A, 5);
insert(&B, 6);
insert(&B, 8);
display(&A);
display(&B);
return 0;
}
Activity 8:
We can create a static linked list by using the an array of structure;

#include <iostream>
using namespace std;
const int MAX_SIZE = 10; // Maximum number of nodes in the
linked list

struct Node {
int data; // Data for the node
int next; // Index of the next node in the array
};

// Static array to hold the nodes


Node list[MAX_SIZE];

// Initialize a free list to keep track of unused nodes


int freeListHead = 0; // Points to the first free node in the
array
int size = 0; // Number of nodes currently used

// Initialize the list


void initList() {
for (int i = 0; i < MAX_SIZE - 1; ++i) {
list[i].next = i + 1; // Link each node to the next
}
list[MAX_SIZE - 1].next = -1; // The last node's next is -
1 (no free nodes after this)
}
// Get a new node from the free list
int getNode() {
if (freeListHead == -1) {
cout << "List is full!" << endl;
return -1; // No space left
}
int index = freeListHead;
freeListHead = list[freeListHead].next;
return index;
}

// Release a node back to the free list


void releaseNode(int index) {
list[index].next = freeListHead;
freeListHead = index;
}

// Add a node to the list


void addNode(int data) {
int newNode = getNode();
if (newNode == -1) return; // No space to add new node

list[newNode].data = data;
list[newNode].next = -1; // Initially, it does not point
to any other node

if (size == 0) {
// Adding the first node
list[newNode].next = -1;
} else {
// Add at the end of the list
int current = 0;
while (list[current].next != -1) {
current = list[current].next;
}
list[current].next = newNode;
}
++size;
}

// Print the list


void printList() {
int current = 0;
while (current != -1) {
cout << list[current].data << " -> ";
current = list[current].next;
}
cout << "NULL" << endl;
}

int main() {
initList();

addNode(10);
addNode(20);
addNode(30);

printList(); // Should print: 10 -> 20 -> 30 -> NULL

return 0;
}

Output
10 -> 20 -> 30 -> NULL

8) Graded Lab Tasks


Note: The instructor can design graded lab activities according to the level of difficulty and
complexity of the solved lab activities. The lab tasks assigned by the instructor should be
evaluated in the same lab.

Lab Task 1
use a simple array to store the marks of 10 students from quiz 1 of data structure course, the obtained
marks are considered out of 15. Write function to compute average marks for the entire class.

Lab Task 2
Write a program using float ArrayList to store temperature of a week, and write functions to find week
maximum temprature.

Lab Task 3
By using the concept of static linked list, write functions for the following operations.
1) Insert a value at end of list
2) Remove First value from list
3) Remove last value from list
4) Display List in Reverse
5) Remove a value from a given index.
Lab 03
Dynamic Singly Linked List

Objective:

In this lab, students will learn how to use pointers, implement linked list, implement doubly linked list and
related algorithms such as insertion, deletion and traversals.

Activity Outcomes:

The activities provide hands - on practice with the following topic

 Creating Node using Strcutures


 Inserting a new node in list
 Displaying a list
 Removing a node from list
 Recursively display a list
 Merging a list
9) Useful Concepts
In C/C++ programming we can access memory locations, by their address, and to store that address we
need variables that can store memory addresses instead of normal variable that stores values. The variables
that store memory addresses are different than the normal variables. E.g. if we have a variable of int type
a=10, we can get its address by & (ampersand) symbol, i.e. &a, using cout we can check the location of
variable in memory (that will be displayed in a hexadecimal number in the format of 0xF203AB etc).

To store a variable address we need a pointer, that can be declared as following;

int a =10;
int *b = &a;
cout << b << *b

10) Solved Lab Activites


Sr.No Allocated Time Level of Complexity CLO Mapping
1 5 Mins Low CLO-4
2 5 Mins Low CLO-4
3 5 Mins Low CLO-4
4 5 Mins Low CLO-4
5 10 Mins Low CLO-4
6 5 Mins Medium CLO-4
7 5 Mins Low CLO-4
8 5 Mins Low CLO-4
9 5 Mins Low CLO-4
10 10 Mins Medium CLO-4
11 5 Mins Low CLO-4
12 10 Mins Medium CLO-4
13 15 Mins High CLO-4
14 5 Mins Low CLO-4
15 5 Mins Low CLO-4
16 10 Mins Medium CLO-4

Activity 1:
Program to define a pointer and use in display the address and contents of an integer variable.

Solution:
#include<iostream>

using namespace std;


int main()
{
int a=10;
int *b=&a;

cout<<"the variable is stored at " << b;


cout<<”the value of a is pointed by b”<< *b;
return 0;
}

Activity 2:
Use Structure to define a node of integer value.
A node strcuture

50
int data next

#include <iostream>
using namespace std;
int main () {
struct node { //definition of node structure
int data;
node* next;
};
node first; // a single variable of node type;
first.data=50;
first.next=NULL;
cout << “value stored in node is “<< first.data;
return 0;
}

Output
value stored in node is 50

Activity 3:
Creating two nodes and connecting together.

#include <iostream>
using namespace std;
int main () {
struct node { //definition of node structure
int data;
node* next;
};
node first, second; // a two variables of node type;
first.data=50;
second.data=60;
first.next=&second; //linked the first node to the second
cout << “value of first and second node “<< first.data
<< “, “ << first.next->data;
return 0;
}

Output
Value of first and second node 50, 60

Activity 4:
Create a linked list of three nodes, and traverse through a loop.

#include <iostream>
using namespace std;
struct node { //definition of node structure
int data;
node* next;
};

int main () {
node first, second, third;
first.data = 50; // set values of nodes
second.data = 60;
third.data = 70;
first.next = &second; // first node linked to second
second.next = &third; // similarly second node linked to third
third.next = NULL; // third node is not connected to any node
node *current=&first; // for purpose of loop we initialized
// loop variable current with first node
while (current!=NULL) {
cout << current->data ;
current = current->next;
}
return 0;
}

Output
Result is 50 60 70

Activity 5:
Create a function that add a new node at start of a linked list, and write a function to display the list.

#include <iostream>
using namespace std;

struct node { //definition of node structure


int data;
node* next;
};
void insert_start(int v, node *head); // function prototype
void display(node *head); // this will display linked list
int main () {
node *head=NULL;// there is no node at the beginning
insert_start(50,head);
insert_start(60, head);
insert_start(70, head);
display(head);
return 0;
}
void insert_start(int v, node *head)
{
node *newNode = new node;
newNode->data = v;
newNode->next = head;
head = newNode;
}
void display(node *starting)
{
node *current = starting;
while (current!=NULL) {
cout << current->data ;
current = current->next;
}
}
Output
70, 60, 50
Activity 6:
Create a function that add a new node at end of a linked list.

#include <iostream>
using namespace std;

struct node { //definition of node structure


int data;
node* next;
};
void insert_at_end(int v, node *head); // function prototype
void display(node *head); // this will display linked list
int main () {
node *head=NULL;// there is no node at the beginning
insert_at_end(50,head);
insert_at_end(60, head);
insert_at_end(70, head);
display(head);
return 0;
}
void insert_at_end(int v, node *head)
{
node *newNode = new node;
node *lastNode = head;
newNode->data = v;
newNode->next = NULL;
if (head = NULL) // list is empty
{ head = newNode;
return;
}
while (lastNode->next!=NULL) // moving to last node
lastNode = lastNode->next;
newNode->next = head;
}
void display(node *starting)
{
node *current = starting;
while (current!=NULL) {
cout << current->data ;
current = current->next;
}
}

Output
50 60 70

Activity 7:
Assume we have a list of values 50,60,70,80,90,100; we can get a value that is the first value in the list,
for this purpose we write a function getFirst that will return an integer from a given list.

NOTE: the following code is added to the previous Activitiy’s code.

int getFirst(node *head)


{
if (head==NULL)
return -1; // in case list is empty
return head->data;
}

Activity 8:
Write a function to get last value of a list;
NOTE: the following code is added to the Activitiy 6’s code.

int getLast(node *head)


{
if (head==NULL)
return -1; // in case list is empty
node *lastNode=head;
while (lastNode->next!=NULL)
lastNode = lastNode->next;
return lastNode->data;
}

Activity 9:
Write a function named exists that will search for a number in a list, and return true if it’s in the list.
bool exists(int n, node *head)
{
if (head==NULL)
return false; // in case list is empty
node *current = head;
while (current != NULL)
{
if (current->data == n)
return true;
current=current->next;
}
return false;
}

Activity 10:
Write a function named search that will find address of a node for a given number in a list.

node* search(int n, node *head)


{
if (head==NULL)
return NULL; // in case list is empty
node *current = head;
while (current != NULL)
{
if (current->data == n)
return current;
current=current->next;
}
return NULL;
}
Activity 11:
Write a function that will delete first node of a given list;

void removeFirst(node *head)


{
if (head==NULL)
return; // in case list is empty
node unlinked_node = head; // this will extract a node
head=head->next;
delete unlinked_node; // this statement will free memory
}
Activity 12:
Write a function that will delete last node of a given list;

void removeLast(node *head)


{
if (head==NULL)
return; // in case list is empty
node last_node = head; // this is the last node
node penultimate = head; // this is the second last node
while (last_node->next!=NULL) {
penultimate = last_node;
last_node = last_node->next;
}
penultimate->next = NULL; // unlink the last node
delete last_node; // this statement will free memory
}

Activity 13:
Write a function that will find a given value in list and then removes it from list.

void removeSpecific(int value, node *head)


{
if (head==NULL)
return; // in case the list is empty
node removal_node = head; // this node is to be removed
node previous_node= head; // this node is previous of
// removal_node
// the following loop will search for the node to be removed
while (removal_node->next!=NULL) {
if (removal_node->data == value) break;
previous_node = removal_node->next;
removal_node = removal_node->next;
}
if (removal_node==NULL) return; // the value doesnot exists
previous_node->next = removal_node->next; // relink nodes
delete removal_node; // this statement will free memory
}

Activity 14:
Write a function that will display a list using recursion.

void show(node *current)


{
if (current==NULL)
return;
else{
cout << current->data ;
show(current->next);
}
}

Activity 15:
Write a function that will display a list in reverse order using recursion.

void show(node *current)


{
if (current==NULL)
return;
else{
show(current->next);
cout << current->data ;
}
}
Activity 16:
Make a list with two ends e.g. head and tail;

#include <iostream>
using namespace std;
struct node { //definition of node structure
int data;
node* next;
};
void insert_at_start(int v, node *head, node *tail);
void insert_at_end(int v, node *tail); // function prototype
void display(node *head); // this will display linked list
int main () {
node *head=NULL;// there is no node at the beginning
node *tail=NULL;
insert_at_end(50,head);
insert_at_end(60, head);
insert_at_start(70, head);
display(head);
return 0;
}
void insert_at_start(int v, node *head, node *tail)
{
node *newNode = new node;
newNode->data = v;
newNode->next = head;
head = newNode;
if (head->next==NULL) // if it’s the first node
tail = newNode; // or tail = head as well
}
void insert_at_end(int v, node *head, node *tail)
{
node *newNode = new node;
if (head = NULL) // list is empty
{ head = newNode;
tail = newNode;
}
else
{ tail->next= newNode;
tail = newNode;
}
}

11) Graded Lab Tasks


Note: The instructor can design graded lab activities according to the level of difficulty and
complexity of the solved lab activities. The lab tasks assigned by the instructor should be
evaluated in the same lab.
Lab Task 1
Find minimum value in a given linked list.

int minimum(node *head)

Lab Task 2

Write a recursive function that finds sum of values of all nodes in a singly linked list.

int sum(Node *head)

Lab Task 3
If two lists are given, write a method which will merge two lists in to a new list.
e.g. list a = {1,3,7,5}

list b = {6,10,8,2,4}

c = union(a,b)

list c = {1,3,7,5, 6,10,8,2,4}

Lab Task 4
If two lists are given, and both contains integer values in ascending order, write a function which will
combine two lists, in a new list, while maintaining the order of values.

e.g. list a = {1,3,5,7}

list b = {2,4,6,8,10}

list c = {1,2,3,4,5,6,7,8,10}

c = merge(a,b)

Lab Task 5
If a lists is given that contains integer values, write a function which will remove all prime numbers from
the list.

e.g. list a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}

list b = {2,4,6,8,10}

list c = {1,2,3,4,5,6,7,8,10}

c = merge(a,b)

You might also like