You are on page 1of 42

Institute of southern Punjab, Multan

Department Of Computer Science

LAB MANUAL
DATA STRUCTURES AND ANALYSIS OF ALGORITHMS
SPRING-2K19

Qasim Niaz
Lecturer
Objective:

In order to develop efficient software systems, it is essential that efficient algorithms and
appropriate data structures are used. This course will help the students to develop efficient
data structures and algorithms in a systematic manner. The students are advised to follow the
following steps for each experiment.

1. Problem definition

2. Algorithm Design
3. Program development either in C or C++ language 4. Execution of the program

5. Maintain a suitable observation book for the same.


Institute of Southern Punjab, Multan

Department of Computer Science

Data Structures & Analysis of Algorithms Lab Manual

List of Experiments

I. Iterative Statements, Conditional Statements, Pointers, Functions II.


Recusrion

III. Linear Search, Binary Search,

IV. Finding the maximum element in an array, Insert an element at any position in
array, Delete an element at any position in array.

V. Recursion implementation.(using factorial function and Binary Search)

VI. Sorting Algorithms(Selection, Insertion, MERGE, Quick)

VII. Sorting Algorithms(Bubble, Heap, Shell, Radix, Bucket)

VIII. Implement stack using array.(PUSH,POP,ISEMPTY,TOP/PEEK) Operations

IX. Implementation of singly linked list


• Insert an element in the beginning of singly linked list.
• Insert an element in the end of singly linked list.
• Insert an element at any position in singly linked list.
• Counting the number of nodes in singly linked list

X. Implementation of a Doubly Linked List

XI. Implementation of a queue using Array(En-Queue, DE-Queue, Priority Queue)

XII. DFS, BFS using Arrays & Link List

XIII. Implementation of Hashing and Indexing

XIV. Implementation of Addressing and Chaining

XV. Implementation of Trees and Graphs


Department of Computer Science
Institute of Southern Punjab, Multan

Page 3
LAB 01
LAB Task
Review the programming fundamentals Lab Manual
LAB 02 LAB Task Task # 01: Recursive Function of
Factorial.
Solution
#include<iostream>
using namespace std;
int fact(int n)
{if((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
int main()
{
int n;
cout<<"Enter value of for Factorial";
cin>>n;
cout<<"Factorial of "<<n<<" is "<<fact(n);
return 0;
}

Task # 02: Fibonacci Series using Recursion


#include<bits/stdc++.h>
using namespace std;
int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
} int main
()
{
int n = 9;
cout << fib(n);
getchar();
return 0;
}

Department of Computer Science


Institute of Southern Punjab, Multan

Page 5
Lab # 02
Assignment # 02

Lab # 03
LAB Task
Task#01: Write a Program to implement the linear search Algorithm?

#include <iostream>

using namespace std;

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


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

int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, x);
(result == -1)?

cout<<"Element is not present in array" :


cout<<"Element is present at index " <<result;

return 0; }

Task#02: Write a program to implement the binary search algorithm using recursive &
non-recursive functions? #include <stdio.h>
#define MAX_LEN 10
/* Non-Recursive function*/
void b_search_nonrecursive(int l[],int num,int ele)
{
int l1,i,j, flag = 0;
l1 = 0; i = num-1;
while(l1 <= i)
{
j = (l1+i)/2;
if( l[j] == ele)
{

Department of Computer Science


Institute of Southern Punjab, Multan

Page 6
printf("\nThe element %d is present at position %d in list\n",ele,j);
flag =1; break; } else if(l[j] < ele) l1 = j+1;
else i = j-1;
}
if( flag == 0)
printf("\nThe element %d is not present in the list\n",ele);
}

/* Recursive function*/
int b_search_recursive(int l[],int arrayStart,int arrayEnd,int a)
{ int
m,pos;
if (arrayStart<=arrayEnd)
{
m=(arrayStart+arrayEnd)/2;
if (l[m]==a)
return m; else
if (a<l[m])
return b_search_recursive(l,arrayStart,m-1,a);
else
return b_search_recursive(l,m+1,arrayEnd,a);
} return
-1;
}
void read_list(int l[],int n)
{
int i;
printf("\nEnter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&l[i]);
}
void print_list(int l[],int n)
{
int i;
for(i=0;i<n;i++) printf("%d\
t",l[i]);
}
/*main function*/
main() {
int l[MAX_LEN], num, ele,f,l1,a;
int ch,pos;
clrscr();
printf("======================================================");
printf("\n\t\t\tMENU");
printf("\n=====================================================");
printf("\n[1] Binary Search using Recursion method"); printf("\
n[2] Binary Search using Non-Recursion method");
Department of Computer Science
Institute of Southern Punjab, Multan

Page 7
printf("\n\nEnter your Choice:");
scanf("%d",&ch);

if(ch<=2 & ch>0)


{
printf("\nEnter the number of elements : ");
scanf("%d",&num);
read_list(l,num);
printf("\nElements present in the list are:\n\n");
print_list(l,num);
printf("\n\nEnter the element you want to search:\n\n");
scanf("%d",&ele);

switch(ch)
{
case 1:printf("\nRecursive method:\n");
pos=b_search_recursive(l,0,num,ele);
if(pos==-1)
{
printf("Element is not found");
}
else
{
printf("Element is found at %d position",pos);
}
//getch();
break;

case 2:printf("\nNon-Recursive method:\n");


b_search_nonrecursive(l,num,ele);
//getch();
break;
}
}
//
getch(); }

Task#3: Write a program to implement the Selection sort on the given list?

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

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 8
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " "; cout
<< endl;
} int
main()
{
int size;
cin>>size;
int arr[size];
for(int i =0;i<size;i++)
{
cin>>arr[i];
}
selectionSort(arr, size);
cout << "Sorted array: \n";
printArray(arr, size);
return 0;
}
Task # 04: Write a program to implement the insertion sort?
#include <bits/stdc++.h>
using namespace std;
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 9
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Task # 05: Write a program to implement the Merge sort on given array?
#include<stdlib.h>
#include<stdio.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m] // Second
subarray is arr[m+1..r] void merge(int
arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */


int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */


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

L[i] = arr[l + i];


Department of Computer Science
Institute of Southern Punjab, Multan

Page 10
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{

Department of Computer Science


Institute of Southern Punjab, Multan

Page 11
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there


are any */ while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there


are any */ while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the


sub-array of arr to be sorted */ void
mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

merge(arr, l, m, r);
}
}

Department of Computer Science


Institute of Southern Punjab, Multan

Page 12
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]); printf("\
n");
}

/* Driver program to test above functions */


int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size); return 0;
}
Task 06: Write a program to implement the Quick sort on a given array?
#include <bits/stdc++.h>
using namespace std;
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot int i =
(low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);

Department of Computer Science


Institute of Southern Punjab, Multan

Page 13
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index, high
--> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1); cout
<< "Sorted array: \n";
printArray(arr, n);
return 0;
}
Task # 07: Write a program to implement the bubble sort on given list?
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
Department of Computer Science
Institute of Southern Punjab, Multan

Page 14
}
// An optimized version of Bubble Sort
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 no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]); printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n); printf("Sorted
array: \n");
printArray(arr, n);
return 0;
}

Department of Computer Science


Institute of Southern Punjab, Multan

Page 15
LAB # 03
Assignment # 03

LAB # 04
LAB Task Task #

01: Write a program to implement the Heap Sort?

Solution:

#include <iostream>
using namespace std;

// To heapify a subtree rooted with node i which is

// an index in arr[]. n is size of heap

void heapify(int arr[], int n, int i)

int largest = i; // Initialize largest as root

int l = 2*i + 1; // left = 2*i + 1 int

r = 2*i + 2; // right = 2*i + 2 // If left

child is larger than root if (l < n && arr[l]

> arr[largest])

largest = l;

// If right child is larger than largest so far

if (r < n && arr[r] > arr[largest])

largest = r;

// If largest is not root

if (largest != i)

Department of Computer Science


Institute of Southern Punjab, Multan

Page 16
swap(arr[i], arr[largest]); //

Recursively heapify the affected sub-tree

heapify(arr, n, largest);

// main function to do heap sort

void heapSort(int arr[], int n)

// Build heap (rearrange array)


for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

// One by one extract an element from heap

for (int i=n-1; i>=0; i--)

// Move current root to end

swap(arr[0], arr[i]); // call max

heapify on the reduced heap

heapify(arr, i, 0);

/* A utility function to print array of size n */

void printArray(int arr[], int n)

Department of Computer Science


Institute of Southern Punjab, Multan

Page 17
for (int i=0; i<n; ++i)

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

cout << "\n";

// Driver program

int main()

int arr[] = {12, 11, 13, 5, 6, 7};

int n = sizeof(arr)/sizeof(arr[0]);

heapSort(arr, n);

cout << "Sorted array is \n";

printArray(arr, n);
}

Task # 02: Write a program to implement the Radix Sort on the give list?

Solution

#include<iostream>

using namespace std;

// A utility function to get maximum value in arr[]

int getMax(int arr[], int n)

int mx = arr[0];

for (int i = 1; i < n; i++)

if (arr[i] > mx)

mx = arr[i];

Department of Computer Science


Institute of Southern Punjab, Multan

Page 18
return mx;

// A function to do counting sort of arr[] according

to // the digit represented by exp.

void countSort(int arr[], int n, int exp)

int output[n]; // output array

int i, count[10] = {0};

// Store count of occurrences in count[]

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

count[ (arr[i]/exp)%10 ]++;

// Change count[i] so that count[i] now contains actual

// position of this digit in output[]

for (i = 1; i < 10; i++)


count[i] += count[i - 1];

// Build the output array for

(i = n - 1; i >= 0; i--)

output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];

count[ (arr[i]/exp)%10 ]--;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 19
// Copy the output array to arr[], so that arr[] now

// contains sorted numbers according to current digit

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

arr[i] = output[i];

// The main function to that sorts arr[] of size n using

// Radix Sort void

radixsort(int arr[], int n)

// Find the maximum number to know number of digits

int m = getMax(arr, n);

// Do counting sort for every digit. Note that instead

// of passing digit number, exp is passed. exp is 10^i

// where i is current digit number

for (int exp = 1; m/exp > 0; exp *= 10)

countSort(arr, n, exp);

// A utility function to print an array void

print(int arr[], int n)

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

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

Department of Computer Science


Institute of Southern Punjab, Multan

Page 20
// Driver program to test above functions

int main()

int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};

int n = sizeof(arr)/sizeof(arr[0]);

radixsort(arr, n); print(arr, n);

return 0;

Task # 03: Write a program to implement the Bucket Sort on a given list?

Solution

#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

// Function to sort arr[] of size n using bucket sort

void bucketSort(float arr[], int n)

// 1) Create n empty buckets

vector<float> b[n];

// 2) Put array elements in different buckets

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

{ int bi = n*arr[i]; // Index in

bucket b[bi].push_back(arr[i]);

Department of Computer Science


Institute of Southern Punjab, Multan

Page 21
}

// 3) Sort individual buckets

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

sort(b[i].begin(), b[i].end()); //

4) Concatenate all buckets into arr[]

int index = 0;

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

(int j = 0; j < b[i].size(); j++)

arr[index++] = b[i][j];

/* Driver program to test above funtion */

int main()

float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};

int n = sizeof(arr)/sizeof(arr[0]);

bucketSort(arr, n); cout

<< "Sorted array is \n"; for (int

i=0; i<n; i++) cout << arr[i]

<< " ";

return 0;

Task # 04: Write a program to implement the Shell Sort on a given list?

Solution

Department of Computer Science


Institute of Southern Punjab, Multan

Page 22
#include <iostream>

using namespace std;

/* function to sort arr using shellSort */

int shellSort(int arr[], int n)

// Start with a big gap, then reduce the gap

for (int gap = n/2; gap > 0; gap /= 2)

// Do a gapped insertion sort for this gap size. The first gap elements a[0..gap-1] are already
// in gapped order keep adding one more element until the entire array is gap sorted

for (int i = gap; i < n; i += 1)

// add a[i] to the elements that have been gap sorted save a[i] in temp and make a hole at
//position i

int temp = arr[i];

// shift earlier gap-sorted elements up until the correct location for a[i] is found

int j;

for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)

arr[j] = arr[j - gap];

// put temp (the original a[i]) in its correct location

arr[j] = temp;

return 0;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 23
} void printArray(int arr[], int

n)

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

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

} int

main()

int arr[] = {12, 34, 54, 2, 3}, i;

int n = sizeof(arr)/sizeof(arr[0]);

cout << "Array before sorting: \n";

printArray(arr, n); shellSort(arr,

n); cout << "\nArray after sorting: \n";

printArray(arr, n);

return 0;

LAB # 04
Assignment

LAB # 05
LAB Task
Task # 01: Write a program to implement the Stack Data structure? Solution
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000 class
Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);

Department of Computer Science


Institute of Southern Punjab, Multan

Page 24
int pop(); int
peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
} int
Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
} int
Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{

Department of Computer Science


Institute of Southern Punjab, Multan

Page 25
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
return 0;
}
LAB # 05
Assignment
LAB # 06
LAB Task

Task # 01: Write a program to implement the Queue Data structures?

Solution

#include <bits/stdc++.h>

using namespace std;

class Queue

public:

int front, rear, size;

unsigned capacity; int*

array;

};

Queue* createQueue(unsigned capacity)

Queue* queue = new Queue();

queue->capacity = capacity;

queue->front = queue->size = 0;

queue->rear = capacity - 1; // This is important, see the enqueue queue-

>array = new int[(queue->capacity * sizeof(int))];

Department of Computer Science


Institute of Southern Punjab, Multan

Page 26
return queue;

int isFull(Queue* queue)

return (queue->size == queue->capacity);

int isEmpty(Queue* queue)


{

return (queue->size == 0);

void enqueue(Queue* queue, int item)

if (isFull(queue))

return;

queue->rear = (queue->rear + 1) % queue->capacity;

queue->array[queue->rear] = item; queue->size =

queue->size + 1; cout << item << " enqueued to queue\

n";

int dequeue(Queue* queue)

if (isEmpty(queue))

return INT_MIN;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 27
int item = queue->array[queue->front]; queue-

>front = (queue->front + 1) % queue->capacity; queue-

>size = queue->size - 1; return item;

// Function to get front of queue

int front(Queue* queue)

if (isEmpty(queue))

return INT_MIN;
return queue->array[queue->front];

// Function to get rear of queue int

rear(Queue* queue)

if (isEmpty(queue))

return INT_MIN;

return queue->array[queue->rear];

// Driver code

int main()

Queue* queue = createQueue(1000);

enqueue(queue, 10); enqueue(queue, 20);

enqueue(queue, 30); enqueue(queue, 40);

cout<<dequeue(queue)<<" dequeued from queue\n";


Department of Computer Science
Institute of Southern Punjab, Multan

Page 28
cout << "Front item is " << front(queue) << endl;

cout << "Rear item is " << rear(queue) << endl;

return 0;

LAB # 06
Assignment

LAB # 07
LAB Task
Task # 01: Write a program to implement the Linked List Data Structures with all its
operations?
Solution
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node { int
info; struct node
*next;
} *start; class
single_llist
{ publi
c:
node* create_node(int);
void insert_begin();
void insert_pos(); void
insert_last(); void
delete_pos(); void
sort(); void search();
void update(); void
reverse(); void
display(); single_llist()
{
start = NULL;
}
};
main()
{
int choice, nodes, element, position, i;
single_llist sl;
start = NULL;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 29
while (1)
{
cout<<endl<<"---------------------------------"<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<"---------------------------------"<<endl;
cout<<"1.Insert Node at beginning"<<endl;
cout<<"2.Insert node at last"<<endl; cout<<"3.Insert
node at position"<<endl; cout<<"4.Sort Link
List"<<endl; cout<<"5.Delete a Particular
Node"<<endl; cout<<"6.Update Node Value"<<endl;
cout<<"7.Search Element"<<endl; cout<<"8.Display
Linked List"<<endl; cout<<"9.Reverse Linked List
"<<endl;
cout<<"10.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)

{ case
1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begin();
cout<<endl;
break; case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last(); cout<<endl;
break; case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_pos();
cout<<endl;
break; case 4:
cout<<"Sort Link List: "<<endl;
sl.sort();
cout<<endl;
break; case 5:
cout<<"Delete a particular node: "<<endl;
sl.delete_pos();
break; case 6:
cout<<"Update Node Value:"<<endl;
sl.update(); cout<<endl; break;
case 7:
cout<<"Search element in Link List: "<<endl;
sl.search(); cout<<endl; break;
case 8:
cout<<"Display elements of link list"<<endl;
sl.display(); cout<<endl; break;
case 9:
Department of Computer Science
Institute of Southern Punjab, Multan

Page 30
cout<<"Reverse elements of Link List"<<endl;
sl.reverse();
cout<<endl; break;
case 10:
cout<<"Exiting..."<<endl;
exit(1); break;
default:
cout<<"Wrong choice"<<endl;
}
}
}
node *single_llist::create_node(int value)
{ struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
} else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
void single_llist::insert_begin()
{ int
value;
cout<<"Enter the value to be inserted: ";
cin>>value; struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{ start = temp;
start->next = NULL;
} else {
p = start; start =
temp; start-
>next = p;
}
cout<<"Element Inserted at beginning"<<endl;
}
void single_llist::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";

Department of Computer Science


Institute of Southern Punjab, Multan

Page 31
cin>>value; struct
node *temp, *s;
temp = create_node(value);
s = start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL; s-
>next = temp;
cout<<"Element Inserted at last"<<endl;
}
void single_llist::insert_pos()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value; struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{ s = s-
>next;
counter++;
} if (pos
== 1)
{ if (start ==
NULL)
{ start =
temp;
start->next = NULL;
} else {
ptr = start; start =
temp; start->next
= ptr;
}
}
else if (pos > 1 && pos <= counter)
{ s = start; for
(i = 1; i < pos; i++) {
ptr = s; s = s->next;
}
ptr->next = temp;
temp->next = s;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 32
}
else
{
cout<<"Positon out of range"<<endl;
}
}
void single_llist::sort()
{ struct node *ptr,
*s; int value; if
(start == NULL)
{
cout<<"The List is empty"<<endl;
return;
}
ptr = start; while
(ptr != NULL)
{
for (s = ptr->next;s !=NULL;s = s->next)
{
if (ptr->info > s->info)
{ value =
ptr->info; ptr->info
= s->info;
s->info = value;
}
} ptr = ptr-
>next;
}
}
void single_llist::delete_pos()
{ int pos, i, counter =
0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos; struct node *s, *ptr;
s = start;
if (pos == 1)
{ start = s-
>next;
}
else

Department of Computer Science


Institute of Southern Punjab, Multan

Page 33
{
while (s != NULL)
{ s = s-
>next;
counter++;
}
if (pos > 0 && pos <= counter)
{ s = start;
for (i = 1;i < pos;i++)
{ ptr
= s; s = s-
>next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
}
}
void single_llist::update()
{ int value, pos,
i;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the node postion to be updated: ";
cin>>pos; cout<<"Enter the new value: ";
cin>>value; struct node *s, *ptr; s = start;
if (pos == 1) {
start->info = value;
}
else
{ for (i = 0;i < pos -
1;i++)
{
if (s == NULL)
{
cout<<"There are less than "<<pos<<" elements";
return; }
s = s->next;
}
Department of Computer Science
Institute of Southern Punjab, Multan

Page 34
s->info = value;
}
cout<<"Node Updated"<<endl;
}
void single_llist::search()
{ int value, pos =
0; bool flag =
false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the value to be searched: ";
cin>>value; struct node *s; s = start;
while (s != NULL)

{ pos+
+;
if (s->info == value)
{ flag
= true;
cout<<"Element "<<value<<" is found at position "<<pos<<endl;
} s = s-
>next;
} if (!
flag)
cout<<"Element "<<value<<" not found in the list"<<endl;
}
void single_llist::reverse()
{
struct node *ptr1, *ptr2, *ptr3;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
if (start->next == NULL)
{ return; }
ptr1 = start; ptr2 =
ptr1->next; ptr3 =
ptr2->next; ptr1-
>next = NULL;
ptr2->next = ptr1;
while (ptr3 != NULL)

Department of Computer Science


Institute of Southern Punjab, Multan

Page 35
{ ptr1 = ptr2;
ptr2 = ptr3; ptr3 = ptr3-
>next; ptr2->next =
ptr1;
}
start = ptr2;
}
void single_llist::display()
{ struct node
*temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
} temp =
start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
LAB # 07
Assignment

LAB # 08
LAB Task
Task # 01: Write a program to implement the Doubly Linked list with its operations?
Solution
#include <iostream>
using namespace std;
struct Node { int
data; struct Node*
next; struct Node*
prev;
};
void insert_front(struct Node** head, int new_data)
{
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = (*head);
newNode->prev = NULL; if
((*head) != NULL) (*head)->prev =
newNode;
(*head) = newNode;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 36
}
void insert_After(struct Node* prev_node, int new_data)
{
if (prev_node == NULL) {
cout<<"Previous node is required , it cannot be NULL";
return; }
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = prev_node->next;
prev_node->next = newNode;
newNode->prev = prev_node; if
(newNode->next != NULL)
newNode->next->prev = newNode;
}
void insert_end(struct Node** head, int new_data)
{
struct Node* newNode = new Node; struct Node*
last = *head; //set last node value to head
newNode->data = new_data;
newNode->next = NULL; if
(*head == NULL)
{ newNode->prev = NULL;
*head = newNode;

return; }
while (last->next != NULL)
last = last->next; last->next
= newNode; newNode-
>prev = last;
return;
}
void displayList(struct Node* node) {
struct Node* last; while (node
!= NULL) { cout<<node-
>data<<"<==>"; last = node;
node = node->next;
}
if(node == NULL)
cout<<"NULL";
}
int main() {
/* Start with the empty list */
struct Node* head = NULL;
insert_end(&head, 40);
insert_front(&head, 20);

Department of Computer Science


Institute of Southern Punjab, Multan

Page 37
insert_front(&head, 10);
insert_end(&head, 50);
insert_After(head->next, 30);
cout<<"Doubly linked list is as follows: "<<endl;
displayList(head); return 0;
}

LAB 08
Assignment

LAB 09
LAB Task
Task # 01: Write a program to implement the stack using linked list?
Solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* link;
}; struct Node*
top; void push(int
data)
{
struct Node* temp; temp = new
Node(); if (!temp) { cout
<< "\nHeap Overflow";
exit(1);
}
temp->data = data; temp-
>link = top;
top = temp;
} int
isEmpty()
{
return top == NULL;
} int
peek()
{
if (!isEmpty())
return top->data;
else exit(1);
} void
pop()
{
struct Node* temp; if (top == NULL) {
cout << "\nStack Underflow" << endl;
exit(1);

Department of Computer Science


Institute of Southern Punjab, Multan

Page 38
}
else { temp =
top; top = top->link;
temp->link = NULL;
free(temp);
}
} void
display()
{
struct Node* temp; if (top ==
NULL) { cout << "\nStack
Underflow";
exit(1);
}
else { temp =
top; while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->link;
}
}
}
// Driver Code
int main()
{
push(11);
push(22);
push(33);
push(44);
display();
cout << "\nTop element is %d\n" << peek();
pop();
pop();
display();
cout << "\nTop element is %d\n" << peek();
return 0;
}
LAB # 09
Assignments

LAB # 10
LAB Task

Task # 01: Write a program to implement the Queue data structures using linked list?

Department of Computer Science


Institute of Southern Punjab, Multan

Page 39
Solution

#include <bits/stdc++.h>

using namespace std;

struct QNode {

int data;

QNode* next;

QNode(int d)

data = d;

next = NULL;

};

struct Queue {

QNode *front, *rear;

Queue()

front = rear = NULL;

void enQueue(int x)

// Create a new LL node

QNode* temp = new QNode(x);


// If queue is empty, then

// new node is front and rear both

Department of Computer Science


Institute of Southern Punjab, Multan

Page 40
if (rear == NULL) {

front = rear = temp;

return;

// Add the new node at

// the end of queue and change rear

rear->next = temp;

rear = temp;

// Function to remove

// a key from given queue q

void deQueue()

// If queue is empty, return NULL.

if (front == NULL)

return;

// Store previous front and

// move front one node ahead

QNode* temp = front;

front = front->next;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 41
// If front becomes NULL, then

// change rear also as NULL

if (front == NULL)

rear = NULL;

delete (temp);

};

// Driven Program

int main()

Queue q;

q.enQueue(10);

q.enQueue(20);

q.deQueue();

q.deQueue();

q.enQueue(30);

q.enQueue(40);

q.enQueue(50);

cout << "Queue Front : " << (q.front)->data << endl;

cout << "Queue Rear : " << (q.rear)->data;

Department of Computer Science


Institute of Southern Punjab, Multan

Page 42

You might also like