0% found this document useful (0 votes)
15 views140 pages

Ibrahim Iqbal DS Lab Manuals 1 to 7

Uploaded by

Tahir2 Siddiqui
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)
15 views140 pages

Ibrahim Iqbal DS Lab Manuals 1 to 7

Uploaded by

Tahir2 Siddiqui
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/ 140

UNIVERSITY OF

MANAGEMENT &
TECHNOLOGY

Name: Ibrahim Iqbal


ID: 23018020022
Subject: Data Structures Lab
Document Title: Lab Manuals
Resource Person: Ms. Jaweria

1
Contents
LAB MANUAL #01 (Stacks using arrays).......................................................................................................3
LAB MANUAL#02 (Infix, Prefix & Postfix)...............................................................................................15
Lab Manual#03 (Queue Using Array).................................................................................................32

2
LAB MANUAL #01 (Stacks using arrays)

Lab Task #1: Implement a stack using an array in C++ with the following functions: • push(): Adds an
item to the top of the stack.

• pop(): Removes and returns the top item from the stack.

• traverse(): Displays all items in the stack.

• sort(): Sorts the stack in ascending or descending order.

• search(): Searches for an item in the stack and returns its index.

• minVal(): Displays Minimum value item in stack.

• maxVal(): Displays Maximum value item in stack.

C++ Code:

#include <iostream>

#include <limits>

using namespace std;

class stack{

private:

int top;

int arr[10];

int index;

int temp;

public:

stack(){

top=-1;

void push(int element){

3
if(top==10-1){

cout<<"The stack is full. Cannot push entered value."<<endl;

}else{

top++;

arr[top]=element;

cout<<"The element pushed is: "<<arr[top]<<endl;

void pop(){

if(top==-1){

cout<<"The stack is empty. Cannot pop anymore elements."<<endl;

}else{

cout<<"The element popped is: "<<arr[top]<<endl;

top--;

void traverse(){

if(top==-1){

cout<<"The stack is empty."<<endl;

}else{

cout<<"The elements present in stack are: ";

for(int i=top;i>=0;i--){

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

4
}

void sort(bool ascending){

if(top==-1){

cout<<"The stack has no values."<<endl;

return;

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

for(int j=0;j<top-i;j++){

if ((ascending && arr[j]>arr[j+1]) || (!ascending && arr[j]<arr[j+1])) {

int temp=arr[j];

arr[j]=arr[j + 1];

arr[j+1]=temp;

cout<<"The stack in "<<(ascending ? "ascending" : "descending")<<" order is: "<<endl;

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

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

cout<<endl;

void search(){

if(top==-1){

cout<<"The stack has no value."<<endl;

}else{

5
cout<<"Enter the index value to search for embedded value (0-9)";

cin>>index;

if(index>=0 && index<10){

cout<<"The element at the "<<index<<" is "<<arr[index]<<endl;

}else{

cout<<"Invalid choice. Choose between 0 and 9."<<endl;

void minVal(){

if(top==-1){

cout<<"The stack has no value."<<endl;

}else{

int minValue=numeric_limits<int>::max();

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

if(arr[i]<minValue){

minValue=arr[i];

cout<<"The minimum value in stack is: "<<minValue<<endl;

void maxVal(){

if(top==-1){

cout<<"The stack has no value."<<endl;

6
}else{

int maxValue=numeric_limits<int>::min();

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

if(arr[i]>maxValue){

maxValue=arr[i];

cout<<"The maximum value in stack is: "<<maxValue<<endl;

};

int main(){

stack s;

int choice, element;

while(true){

cout<<"Press 1 to push."<<endl;

cout<<"Press 2 to pop."<<endl;

cout<<"Press 3 to traverse."<<endl;

cout<<"Press 4 to display elements in descending order."<<endl;

cout<<"Press 5 to display elements in ascending order."<<endl;

cout<<"Press 6 to search elements in the stack."<<endl;

cout<<"Press 7 to search for maximum element in stack."<<endl;

cout<<"Press 8 to search for minimum element in stack."<<endl;

cout<<"Press 9 to exit."<<endl;

7
cout<<"Enter your choice: ";

cin>>choice;

switch(choice){

case 1:

cout<<"Enter element: ";

cin>>element;

s.push(element);

break;

case 2:

s.pop();

break;

case 3:

s.traverse();

break;

case 4:

s.sort(false);

break;

case 5:

s.sort(true);

break;

case 6:

s.search();

break;

case 7:

8
s.maxVal();

break;

case 8:

s.minVal();

break;

case 9:

return 0;

break;

default:

cout<<"Invalid choice. Please choose again."<<endl;

Result:

9
Lab Task #2: Write a function to identify and display any duplicate data in the stack along with their
indices.

C++ code:

#include <iostream>

using namespace std;

int top=-1;

int arr[6];

void insert(int element){

if(top<6){

top++;

arr[top]=element;

}else{

cout<<"Stack is full."<<endl;

10
}

void duplicate(){

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

for(int j=i+1;j<=top;j++){

if(arr[i]==arr[j]){

cout<<"Value "<<arr[i]<<" is similar at indices: "<<i<<" & "<<j<<endl;

int main(){

insert(34);

insert(56);

insert(90);

insert(34);

insert(56);

insert(90);

duplicate();

Results:

11
Lab task #3: Write a C++ program that:

• Takes input for elements of a stack named inputStack.

• Sorts these elements in ascending order.

• Stores the sorted elements in another stack named sortedStack such that the smallest elements are
on the top of sortedStack.

• Display both stacks.

C++ Code:

#include <iostream>

using namespace std;

void sortStack(int inputStack[], int n, int sortedStack[]) {

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

int temp = inputStack[i];

int j = i - 1;

while (j >= 0 && sortedStack[j] > temp) {

12
sortedStack[j + 1] = sortedStack[j];

j--;

sortedStack[j + 1] = temp;

int main() {

int n;

cout << "Enter the number of elements in the stack: ";

cin >> n;

int inputStack[n], sortedStack[n];

cout << "Enter the elements of the stack:" << endl;

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

cin >> inputStack[i];

sortStack(inputStack, n, sortedStack);

cout << "Input Stack (Original Order): ";

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

13
cout << inputStack[i] << " ";

cout << endl;

cout << "Sorted Stack (Sorted in ascending order): ";

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

cout << sortedStack[i] << " ";

cout << endl;

return 0;

Results:

14
LAB MANUAL#02 (Infix, Prefix & Postfix)
Lab task#1:

Write code for converting an infix expression to a postfix expression using a stack. This program will
prompt the user to enter an infix expression.

C++ Code:

#include <iostream>

using namespace std;

class Stack {

private:

int top;

char arr[20];

public:

Stack() {

top = -1;

void push(char a) {

arr[++top] = a;

char pop() {

return arr[top--];

15
char top_element() {

return arr[top];

bool empty() {

return top == -1;

};

int precedence(char c) {

if (c == '^')

return 3;

else if (c == '/' || c == '*')

return 2;

else if (c == '+' || c == '-')

return 1;

else

return -1;

void infixToPostfix(char* s) {

Stack st;

char result[20];

int k = 0;

16
for (int i = 0; s[i] != '\0'; i++) {

char c = s[i];

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {

result[k++] = c;

else if (c == '(') {

st.push('(');

else if (c == ')') {

while (!st.empty() && st.top_element() != '(') {

result[k++] = st.pop();

st.pop();

else {

while (!st.empty() && ((precedence(c) < precedence(st.top_element())) ||

(precedence(c) == precedence(st.top_element()) && c != '^'))) {

result[k++] = st.pop();

17
st.push(c);

while (!st.empty()) {

result[k++] = st.pop();

result[k] = '\0';

cout << "Postfix Expression: " << result << endl;

int main() {

char exp[20];

cout << "Enter an infix expression: ";

cin >> exp;

infixToPostfix(exp);

return 0;

Result:

18
Lab Task#2:

Write C++ program to convert infix expression to a prefix expression using a stack.

C++ Code:

#include <iostream>

using namespace std;

class Stack {

private:

int top;

char arr[20];

public:

Stack() {

19
top = -1;

void push(char a) {

arr[++top] = a;

char pop() {

return arr[top--];

char top_element() {

return arr[top];

bool empty() {

return top == -1;

};

int precedence(char c) {

if (c == '^')

return 3;

else if (c == '/' || c == '*')

20
return 2;

else if (c == '+' || c == '-')

return 1;

else

return -1;

void reverse(char* exp, int length) {

for (int i = 0; i < length / 2; i++) {

char temp = exp[i];

exp[i] = exp[length - i - 1];

exp[length - i - 1] = temp;

int length(const char* exp) {

int len = 0;

while (exp[len] != '\0') {

len++;

return len;

21
void infixToPrefix(char* s) {

Stack st;

char result[20];

int len = length(s);

reverse(s, len);

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

if (s[i] == '(') {

s[i] = ')';

} else if (s[i] == ')') {

s[i] = '(';

int k = 0;

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

char c = s[i];

22
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {

result[k++] = c;

else if (c == '(') {

st.push(c);

else if (c == ')') {

while (!st.empty() && st.top_element() != '(') {

result[k++] = st.pop();

st.pop();

else {

while (!st.empty() && ((precedence(c) < precedence(st.top_element())) ||

(precedence(c) == precedence(st.top_element()) && c != '^'))) {

result[k++] = st.pop();

st.push(c);

while (!st.empty()) {

23
result[k++] = st.pop();

result[k] = '\0';

reverse(result, k);

cout << "Prefix Expression: " << result << endl;

int main() {

char exp[20];

cout << "Enter an infix expression: ";

cin >> exp;

infixToPrefix(exp);

return 0;

Result:

24
Lab Task #3:

C++ Code:

25
#include <iostream>

using namespace std;

class Stack {

private:

int top;

char arr[20];

public:

Stack() {

top = -1;

void push(char a) {

arr[++top] = a;

char pop() {

return arr[top--];

char top_element() {

return arr[top];

26
bool empty() {

return top == -1;

};

int precedence(char c) {

if (c == '!')

return 5;

else if (c == '(' || c == ')')

return 4;

else if (c == '*' || c == '/' || c == '%')

return 3;

else if (c == '+' || c == '-')

return 2;

else if (c == '>' || c == '<' || c == '>=' || c == '<=')

return 1;

else

return 0;

void reverse(char* exp, int length) {

for (int i = 0; i < length / 2; i++) {

char temp = exp[i];

27
exp[i] = exp[length - i - 1];

exp[length - i - 1] = temp;

int length(const char* exp) {

int len = 0;

while (exp[len] != '\0') {

len++;

return len;

void infixToPrefix(char* s) {

Stack st;

char result[20];

int len = length(s);

reverse(s, len);

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

28
if (s[i] == '(') {

s[i] = ')';

} else if (s[i] == ')') {

s[i] = '(';

int k = 0;

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

char c = s[i];

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {

result[k++] = c;

else if (c == '(') {

st.push(c);

else if (c == ')') {

while (!st.empty() && st.top_element() != '(') {

result[k++] = st.pop();

29
}

st.pop();

else {

while (!st.empty() && (precedence(c) < precedence(st.top_element()))) {

result[k++] = st.pop();

st.push(c);

while (!st.empty()) {

result[k++] = st.pop();

result[k] = '\0';

reverse(result, k);

cout << "Prefix Expression: " << result << endl;

30
int main() {

char exp[20];

cout << "Enter an infix expression: ";

cin >> exp;

infixToPrefix(exp);

return 0;

Result:

_____________________________________________________________________________________

31
Lab Manual#03 (Queue Using Array)
Lab Task 1: Write a C++ program that implements a simple queue with enqueue, dequeue, and display
operations.

Code:

#include <iostream>

using namespace std;

#define n 5

class queue{

private:

int* arr;

int front;

int back;

public:

queue(){

front=-1;

back=-1;

arr=new int[n];

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

void push(int a){

if(back==n-1){

cout<<"The queue is full."<<endl;

return;

}else{

32
back++;

arr[back]=a;

if(front==-1){

front++;

void pop(){

if(front==-1 || front>back){

cout<<"The queue is empty."<<endl;

return;

}else{

front++;

cout<<" "<<endl;

void peek(){

if(front==-1 || front>back){

cout<<"The queue is empty."<<endl;

return;

}else{

cout<<arr[front]<<endl;

33
void display(){

for(int i=front; i<=back; i++){

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

};

int main(){

queue obj;

obj.push(8);

obj.push(34);

obj.push(12);

obj.peek();

obj.display();

obj.pop();

obj.display();

Result:

34
Lab task 2: Modify the simple queue to include a shifting mechanism that shifts elements to the
beginning of the array when space is available at the start, maximizing the queue’s usable space.

Code:

#include <iostream>

using namespace std;

class Queue {

private:

int* arr;

int front, rear, capacity;

public:

Queue(int size) {

cout<<”Ibrahim Iqbal”<<endl;

cout<<”23018020022”<<endl;

capacity = size;

arr = new int[capacity];

front = rear = -1;

~Queue() {

delete[] arr;

bool isEmpty() {

return front == -1;

35
}

bool isFull() {

return (rear + 1) % capacity == front;

void enqueue(int value) {

if (isFull()) {

cout << "Queue is full, cannot enqueue " << value << endl;

return;

if (isEmpty()) {

front = rear = 0;

} else {

rear = (rear + 1) % capacity;

arr[rear] = value;

void dequeue() {

if (isEmpty()) {

36
cout << "Queue is empty, nothing to dequeue." << endl;

return;

for (int i = front; i != rear; i = (i + 1) % capacity) {

arr[i] = arr[(i + 1) % capacity];

if (front == rear) {

front = rear = -1;

} else {

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

int peek() {

if (isEmpty()) {

cout << "Queue is empty." << endl;

return -1;

return arr[front];

37
void display() {

if (isEmpty()) {

cout << "Queue is empty." << endl;

return;

cout << "Queue elements: ";

for (int i = front; i != rear; i = (i + 1) % capacity) {

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

cout << arr[rear] << endl;

};

int main() {

Queue q(5);

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.enqueue(40);

q.enqueue(50);

q.display();

38
q.dequeue();

q.display();

q.enqueue(60);

q.display();

q.dequeue();

q.display();

q.enqueue(70);

q.display();

return 0;

Result:

39
Lab Task 3: Implement a circular queue using a fixed-size array, supporting circular insertion and
deletion.

Code:

#include <iostream>

using namespace std;

#define n 5

class cirq{

int* arr;

int front;

int back;

int cap;

public:

cirq(){

40
cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

front=-1;

back=-1;

arr=new int[n];

cap=n;

void enqueue(int a){

if((back+1)%cap==front){

cout<<"The queue is full."<<endl;

return;

}else{

if(front==-1){

front=0;

back=(back+1)%cap;

arr[back]=a;

cout<<"The value enqueued is: "<<arr[back]<<endl;

return;

void dequeue(){

if(front==-1){

41
cout<<"Queue is empty."<<endl;

return;

}else if(front==back){

front=-1;

back=-1;

}else{

cout<<"The value dequeued is: "<<arr[front]<<endl;

front=(front+1)%cap;

void peek(){

if(front==-1){

cout<<"The queue is empty"<<endl;

return;

}else{

cout<<"The value at front is: "<<arr[front]<<endl;

return;

void display(){

if(front==-1){

cout<<"Queue is empty"<<endl;

return;

}else{

42
cout<<"The elements in queue are: "<<endl;

for(int i=front;i!=back;i=(i+1)%cap){

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

cout<<arr[back]<<endl;

};

int main(){

cirq obj;

obj.enqueue(12);

obj.display();

obj.enqueue(34);

obj.display();

obj.enqueue(67);

obj.display();

obj.enqueue(56);

obj.display();

obj.enqueue(45);

obj.peek();

obj.display();

obj.enqueue(32);

obj.display();

obj.dequeue();

obj.display();

43
obj.dequeue();

obj.display();

obj.dequeue();

obj.peek();

obj.display();

obj.dequeue();

obj.display();

obj.dequeue();

obj.display();

obj.dequeue();

obj.display();

obj.enqueue(78);

obj.display();

obj.enqueue(98);

obj.display();

obj.enqueue(67);

obj.display();

obj.enqueue(13);

obj.display();

Result:

44
Lab Task 4: Write code for a simple queue that automatically sorts elements during insertion. Ensure
that the queue efficiently uses any available empty space by shifting elements when necessary, and
demonstrate the queue’s sorted behavior by enqueuing and dequeuing elements.

Code:

#include <iostream>

#include <algorithm>

using namespace std;

class SortedQueue {

private:

int *arr;

int front, rear, capacity;

public:

45
SortedQueue(int size) {

cout<<”Ibrahim Iqbal”<<endl;

cout<<”23018020022”<<endl;

capacity = size;

arr = new int[capacity];

front = -1;

rear = -1;

~SortedQueue() {

delete[] arr;

bool isEmpty() {

return front == -1;

bool isFull() {

return rear == capacity - 1;

46
void enqueue(int value) {

if (isFull()) {

cout << "Queue is full. Cannot enqueue " << value << endl;

return;

if (front == -1) {

front = 0;

rear++;

arr[rear] = value;

sort(arr + front, arr + rear + 1);

cout << "Enqueued " << value << endl;

void dequeue() {

if (isEmpty()) {

cout << "Queue is empty. Cannot dequeue." << endl;

return;

47
}

cout << "Dequeued " << arr[front] << endl;

for (int i = front; i < rear; i++) {

arr[i] = arr[i + 1];

rear--;

if (rear == -1) {

front = -1;

int peek() {

if (isEmpty()) {

cout << "Queue is empty." << endl;

return -1;

48
return arr[front];

void display() {

if (isEmpty()) {

cout << "Queue is empty." << endl;

return;

cout << "Queue contents: ";

for (int i = front; i <= rear; i++) {

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

cout << endl;

int size() {

if (isEmpty()) return 0;

return rear - front + 1;

};

49
int main() {

SortedQueue q(5);

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.enqueue(5);

q.enqueue(25);

q.display();

cout << "Front element: " << q.peek() << endl;

q.dequeue();

q.dequeue();

q.display();

q.enqueue(15);

50
q.enqueue(12);

q.display();

return 0;

Result:

Lab Task 5: Use your circular queue implementation to simulate three real-life scenarios where circular
queues are commonly used. For each scenario, add comments to explain how the circular queue’s
properties apply to that situation.

Situations used:

1)Round Robin cpu processing

2)Car Toll Booth management system

3}Printer pool

51
Code:

#include <iostream>

using namespace std;

class CircularQueue {

private:

int *arr;

int front, rear, capacity;

public:

// Constructor to initialize the queue with a fixed size

CircularQueue(int size) {

capacity = size;

arr = new int[capacity];

front = rear = -1;

// Destructor to clean up memory

~CircularQueue() {

delete[] arr;

// Check if the queue is empty

bool isEmpty() {

return front == -1;

52
}

// Check if the queue is full

bool isFull() {

return (rear + 1) % capacity == front;

// Insert an element into the queue (enqueue)

void enqueue(int value) {

if (isFull()) {

cout << "Queue is full. Cannot enqueue " << value << endl;

return;

if (front == -1) { // If queue is empty

front = 0;

rear = (rear + 1) % capacity; // Circular increment of rear

arr[rear] = value;

cout << "Enqueued " << value << endl;

// Remove an element from the queue (dequeue)

void dequeue() {

53
if (isEmpty()) {

cout << "Queue is empty. Cannot dequeue." << endl;

return;

cout << "Dequeued " << arr[front] << endl;

// If queue becomes empty after dequeuing

if (front == rear) {

front = rear = -1; // Reset queue to empty

} else {

front = (front + 1) % capacity; // Circular increment of front

// Get the front element of the queue

int peek() {

if (isEmpty()) {

cout << "Queue is empty." << endl;

return -1;

return arr[front];

// Display the current elements of the queue

54
void display() {

if (isEmpty()) {

cout << "Queue is empty." << endl;

return;

cout << "Queue contents: ";

int i = front;

while (i != rear) {

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

i = (i + 1) % capacity;

cout << arr[rear] << endl; // Print the last element at 'rear'

// Return the current size of the queue

int size() {

if (isEmpty()) return 0;

return (rear - front + 1 + capacity) % capacity;

};

// Simulating three real-life scenarios:

void roundRobinScheduling() {

55
cout << "\nRound Robin CPU Scheduling Simulation:" << endl;

CircularQueue queue(4); // 4 processes in the ready queue

// Enqueue processes (representing tasks in the ready queue)

queue.enqueue(1); // Process 1

queue.enqueue(2); // Process 2

queue.enqueue(3); // Process 3

queue.enqueue(4); // Process 4

queue.display();

// Simulate CPU scheduling by dequeuing and re-enqueuing

// Round robin: each process gets CPU for a fixed time, then goes back to the queue.

queue.dequeue(); // Process 1 completes a time slice, goes back to the queue

queue.enqueue(1); // Enqueue Process 1 back

queue.dequeue(); // Process 2 completes a time slice

queue.enqueue(2); // Enqueue Process 2 back

queue.dequeue(); // Process 3 completes a time slice

queue.enqueue(3); // Enqueue Process 3 back

queue.dequeue(); // Process 4 completes a time slice

queue.enqueue(4); // Enqueue Process 4 back

56
queue.display(); // Check the queue contents after round robin scheduling

void tollBoothManagement() {

cout << "\nToll Booth Management Simulation:" << endl;

CircularQueue queue(3); // 3 cars can wait in the toll booth queue

// Enqueue vehicles (cars arriving at the toll booth)

queue.enqueue(101); // Car 101

queue.enqueue(102); // Car 102

queue.enqueue(103); // Car 103

queue.display();

// Simulate toll booth operation (cars getting processed)

queue.dequeue(); // Car 101 processes and leaves the queue

queue.dequeue(); // Car 102 processes and leaves the queue

queue.enqueue(104); // Car 104 arrives at the toll booth

queue.display(); // Display the queue after processing

queue.dequeue(); // Car 103 processes and leaves

queue.dequeue(); // Car 104 processes and leaves

57
void printSpooler() {

cout << "\nPrint Spooler Simulation:" << endl;

CircularQueue queue(3); // 3 print jobs can wait in the queue

// Enqueue print jobs (Jobs waiting to be printed)

queue.enqueue(101); // Print job 101

queue.enqueue(102); // Print job 102

queue.enqueue(103); // Print job 103

queue.display();

// Simulate printing (jobs being processed)

queue.dequeue(); // Print job 101 processed

queue.dequeue(); // Print job 102 processed

queue.enqueue(104); // Print job 104 arrives

queue.display(); // Display the queue after processing

queue.dequeue(); // Print job 103 processed

queue.dequeue(); // Print job 104 processed

int main() {

58
// Simulating three different real-life scenarios

roundRobinScheduling(); // Round-robin CPU scheduling

tollBoothManagement(); // Toll booth vehicle processing

printSpooler(); // Print job handling

return 0;

Result:

59
LAB MANUAL#4(Singly linked list & Circular Singly linked list)

Lab Task 1(A):

Write C++ Programs for LinkedList (single) that supports the following operations: 1. Add: Add a node
with a specific value to the end of the list. 2. Remove: Remove the first node that contains a specific
value. 3. Display: Print all values in the list. 4. Search by Value: Find the index of the first occurrence of a
specific value. 5. Search by Index: Retrieve the value at a specified index. 6. Back Node: Move to the
previous node (if applicable). 7. Next Node: Move to the next node. 8. Copy List: Create a copy of the
entire linked list. 9. Find Duplicate Node Data: Detects and display the index of duplicate data. 10.
Update a List: Update a list adding the nodes at any index.

Code:

#include <iostream>

using namespace std;

class Node {

public:

int data;

Node* next;

Node(int val){

data=val;

next=NULL;

};

class SinglyLinkedList {

private:

Node* head;

60
public:

SinglyLinkedList(){

cout<<”Ibrahim Iqbal”<<endl;

cout<<”23018020022”<<endl;

head=NULL;

void Add(int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

} else {

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

void Remove(int value) {

if (!head) return;

if (head->data == value) {

61
Node* temp = head;

head = head->next;

delete temp;

return;

Node* temp = head;

while (temp->next && temp->next->data != value) {

temp = temp->next;

if (temp->next) {

Node* toDelete = temp->next;

temp->next = temp->next->next;

delete toDelete;

void Display() {

Node* temp = head;

while (temp) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

62
int SearchByValue(int value) {

Node* temp = head;

int index = 0;

while (temp) {

if (temp->data == value) {

return index;

temp = temp->next;

index++;

return -1;

int SearchByIndex(int index) {

Node* temp = head;

int currentIndex = 0;

while (temp) {

if (currentIndex == index) {

return temp->data;

temp = temp->next;

currentIndex++;

63
}

return -1;

void BackNode() {

cout << "Back node operation not supported in singly linked list." << endl;

void NextNode(Node* currentNode) {

if (currentNode && currentNode->next) {

cout << "Next node value: " << currentNode->next->data << endl;

} else {

cout << "No next node." << endl;

SinglyLinkedList* CopyList() {

SinglyLinkedList* newList = new SinglyLinkedList();

Node* temp = head;

while (temp) {

newList->Add(temp->data);

temp = temp->next;

64
}

return newList;

void FindDuplicateNodeData() {

Node* temp1 = head;

Node* temp2;

while (temp1) {

temp2 = temp1->next;

int index = SearchByValue(temp1->data);

while (temp2) {

if (temp2->data == temp1->data) {

cout << "Duplicate value " << temp2->data << " found at index " << index << endl;

temp2 = temp2->next;

temp1 = temp1->next;

void UpdateList(int index, int value) {

Node* newNode = new Node(value);

if (index == 0) {

newNode->next = head;

65
head = newNode;

return;

Node* temp = head;

int currentIndex = 0;

while (temp && currentIndex < index - 1) {

temp = temp->next;

currentIndex++;

if (temp) {

newNode->next = temp->next;

temp->next = newNode;

} else {

cout << "Index out of bounds." << endl;

};

int main() {

SinglyLinkedList list;

list.Add(10);

list.Add(20);

list.Add(30);

66
list.Add(40);

list.Display();

list.Remove(20);

list.Display();

cout << "Index of 30: " << list.SearchByValue(30) << endl;

cout << "Value at index 2: " << list.SearchByIndex(2) << endl;

list.FindDuplicateNodeData();

list.UpdateList(1, 25);

list.Display();

return 0;

Result:

67
Lab Task 1(B): Perform the above tasks for a circular singly linked list.

Code:

#include <iostream>

using namespace std;

class Node {

public:

int data;

Node* next;

Node(int val){

data=val;

next=NULL;

68
};

class CircularLinkedList {

private:

Node* head;

public:

CircularLinkedList(){

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

head=NULL;

void Add(int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

newNode->next = head;

} else {

Node* temp = head;

while (temp->next != head) {

temp = temp->next;

temp->next = newNode;

69
newNode->next = head;

void Remove(int value) {

if (!head) return;

if (head->data == value) {

if (head->next == head) {

delete head;

head = nullptr;

} else {

Node* temp = head;

while (temp->next != head) {

temp = temp->next;

temp->next = head->next;

delete head;

head = temp->next;

return;

Node* temp = head;

while (temp->next != head && temp->next->data != value) {

70
temp = temp->next;

if (temp->next != head) {

Node* toDelete = temp->next;

temp->next = temp->next->next;

delete toDelete;

void Display() {

if (!head) return;

Node* temp = head;

do {

cout << temp->data << " ";

temp = temp->next;

} while (temp != head);

cout << endl;

int SearchByValue(int value) {

if (!head) return -1;

Node* temp = head;

int index = 0;

71
do {

if (temp->data == value) {

return index;

temp = temp->next;

index++;

} while (temp != head);

return -1;

int SearchByIndex(int index) {

if (!head) return -1;

Node* temp = head;

int currentIndex = 0;

do {

if (currentIndex == index) {

return temp->data;

temp = temp->next;

currentIndex++;

} while (temp != head);

return -1;

72
void BackNode(Node* currentNode) {

if (!head || currentNode == head) {

cout << "Back node operation not supported in circular list at head." << endl;

return;

Node* temp = head;

while (temp->next != currentNode) {

temp = temp->next;

cout << "Back node value: " << temp->data << endl;

void NextNode(Node* currentNode) {

if (!head) return;

cout << "Next node value: " << currentNode->next->data << endl;

CircularLinkedList* CopyList() {

CircularLinkedList* newList = new CircularLinkedList();

if (!head) return newList;

Node* temp = head;

do {

73
newList->Add(temp->data);

temp = temp->next;

} while (temp != head);

return newList;

void FindDuplicateNodeData() {

if (!head) return;

Node* temp1 = head;

do {

Node* temp2 = temp1->next;

int index = SearchByValue(temp1->data);

while (temp2 != head) {

if (temp2->data == temp1->data) {

cout << "Duplicate value " << temp2->data << " found at index " << index << endl;

temp2 = temp2->next;

temp1 = temp1->next;

} while (temp1 != head);

void UpdateList(int index, int value) {

Node* newNode = new Node(value);

if (index == 0) {

74
if (!head) {

head = newNode;

newNode->next = head;

} else {

Node* temp = head;

while (temp->next != head) {

temp = temp->next;

temp->next = newNode;

newNode->next = head;

head = newNode;

return;

Node* temp = head;

int currentIndex = 0;

while (temp->next != head && currentIndex < index - 1) {

temp = temp->next;

currentIndex++;

if (temp->next != head || currentIndex == index - 1) {

newNode->next = temp->next;

temp->next = newNode;

} else {

75
cout << "Index out of bounds." << endl;

};

int main() {

CircularLinkedList cll;

cll.Add(10);

cll.Add(20);

cll.Add(30);

cll.Add(40);

cll.Display();

cll.Remove(20);

cll.Display();

cout << "Index of 30: " << cll.SearchByValue(30) << endl;

cout << "Value at index 2: " << cll.SearchByIndex(2) << endl;

cll.FindDuplicateNodeData();

cll.UpdateList(1, 25);

cll.Display();

76
return 0;

Result:

Lab Task 3: Simulate four real-life applications of both linked list types using your implementation. For
each scenario, provide comments to explain how the properties of linked lists make them suitable for
that case.

Result:

1. Music Playlist (Circular Linked List):


o Use Case: A music player where after playing the last song, the player returns to the first
song in a loop.
o Why Circular Linked List?: The circular nature of the list allows the player to loop
indefinitely without checking for end-of-list conditions, making navigation smooth and
constant.

2. Browser History (Singly Linked List):


o Use Case: Storing and navigating the history of web pages visited by a browser.
o Why Singly Linked List?: A singly linked list provides a linear structure where we can
easily add new pages at the end and navigate backward with simple operations.

77
3. Undo/Redo Operations (Circular Linked List):
o Use Case: Implementing undo and redo functionality in applications like text editors.
o Why Circular Linked List?: Circular linked lists allow the user to go back and forth
seamlessly, providing a circular buffer that helps navigate previous states in both
directions.

4. Memory Management (Singly Linked List):


o Use Case: Allocating and deallocating memory blocks dynamically in an operating
system.
o Why Singly Linked List?: Singly linked lists help in managing free and used memory
blocks by linking available memory chunks dynamically without the need for contiguous
space.

_____________________________________________________________________________________

78
Lab Manual 5(Doubly linked list & Circular doubly linked list)

Lab task 1: Write C++ Programs for LinkedList (Doubly) that supports the following operations: 1. Add:
Add a node with a specific value to the end of the list. 2. Remove: Remove the node following FIFO. 3.
Display: Print all values in the list. 4. Search by Index: Retrieve the value at a specified index. 5. Back
Node: Move to the previous node 6. Update a List: Update a list adding the nodes at any index.

Code:

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

Node* prev;

Node(int val){

data=val;

next=NULL;

prev=NULL;

};

79
class DoublyLinkedList {

private:

Node* head;

public:

DoublyLinkedList(){

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

head=NULL;

void Add(int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

} else {

Node* current = head;

while (current->next) {

current = current->next;

current->next = newNode;

newNode->prev = current;

80
}

void Remove() {

if (!head) {

cout << "List is empty, nothing to remove!" << endl;

return;

Node* temp = head;

head = head->next;

if (head) {

head->prev = nullptr;

delete temp;

void Display() const {

if (!head) {

cout << "List is empty!" << endl;

return;

Node* current = head;

while (current) {

cout << current->data << " ";

81
current = current->next;

cout << endl;

int SearchByIndex(int index) const {

if (index < 0) {

cout << "Invalid index!" << endl;

return -1;

Node* current = head;

int count = 0;

while (current) {

if (count == index) {

return current->data;

current = current->next;

count++;

cout << "Index out of range!" << endl;

return -1;

82
int BackNode() const {

if (!head) {

cout << "List is empty!" << endl;

return -1;

Node* current = head;

while (current->next) {

current = current->next;

return current->data;

void UpdateList(int index, int value) {

if (index < 0) {

cout << "Invalid index!" << endl;

return;

Node* newNode = new Node(value);

if (index == 0) {

newNode->next = head;

if (head) {

83
head->prev = newNode;

head = newNode;

return;

Node* current = head;

int count = 0;

while (current) {

if (count == index - 1) {

newNode->next = current->next;

if (current->next) {

current->next->prev = newNode;

current->next = newNode;

newNode->prev = current;

return;

current = current->next;

count++;

cout << "Index out of range!" << endl;

84
~DoublyLinkedList() {

while (head) {

Node* temp = head;

head = head->next;

delete temp;

};

int main() {

DoublyLinkedList list;

list.Add(10);

list.Add(20);

list.Add(30);

list.Add(40);

list.Add(50);

cout << "List after adding nodes: ";

list.Display();

list.Remove();

85
cout << "List after removing the first node: ";

list.Display();

int index = 2;

cout << "Value at index " << index << ": " << list.SearchByIndex(index) << endl;

cout << "Value at the last node: " << list.BackNode() << endl;

list.UpdateList(2, 60);

cout << "List after updating by adding 60 at index 2: ";

list.Display();

cout << "List after adding 5 at the beginning: ";

list.Display();

return 0;

Result:

86
Lab Task 2: Implement the above operations (Q1), using double circular linked list. Make display function
dynamic.

Code:

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

Node* prev;

Node(int val){

87
data=val;

next=NULL;

prev=NULL;

};

class DoublyCircularLinkedList {

private:

Node* head;

public:

DoublyCircularLinkedList(){

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

head=NULL;

void Add(int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

head->next = head;

88
head->prev = head;

} else {

Node* temp = head;

while (temp->next != head) {

temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

newNode->next = head;

head->prev = newNode;

void Remove() {

if (!head) {

cout << "List is empty, nothing to remove!" << endl;

return;

if (head->next == head) {

delete head;

head = nullptr;

} else {

Node* temp = head;

89
head = head->next;

head->prev = temp->prev;

temp->prev->next = head;

delete temp;

void Display() const {

if (!head) {

cout << "List is empty!" << endl;

return;

Node* current = head;

do {

cout << current->data << " ";

current = current->next;

} while (current != head);

cout << endl;

int SearchByIndex(int index) const {

if (index < 0) {

cout << "Invalid index!" << endl;

90
return -1;

Node* current = head;

int count = 0;

do {

if (count == index) {

return current->data;

current = current->next;

count++;

} while (current != head);

cout << "Index out of range!" << endl;

return -1;

int BackNode() const {

if (!head) {

cout << "List is empty!" << endl;

return -1;

return head->prev->data;

91
}

void UpdateList(int index, int value) {

if (index < 0) {

cout << "Invalid index!" << endl;

return;

Node* newNode = new Node(value);

if (index == 0) {

newNode->next = head;

newNode->prev = head->prev;

head->prev->next = newNode;

head->prev = newNode;

head = newNode;

return;

Node* current = head;

int count = 0;

do {

if (count == index - 1) {

newNode->next = current->next;

newNode->prev = current;

92
current->next->prev = newNode;

current->next = newNode;

return;

current = current->next;

count++;

} while (current != head);

cout << "Index out of range!" << endl;

~DoublyCircularLinkedList() {

if (!head) return;

Node* temp = head;

do {

Node* nextNode = temp->next;

delete temp;

temp = nextNode;

} while (temp != head);

};

int main() {

DoublyCircularLinkedList list;

93
list.Add(10);

list.Add(20);

list.Add(30);

list.Add(40);

list.Add(50);

cout << "List after adding nodes: ";

list.Display();

list.Remove();

cout << "List after removing the first node: ";

list.Display();

int index = 2;

cout << "Value at index " << index << ": " << list.SearchByIndex(index) << endl;

cout << "Value at the last node: " << list.BackNode() << endl;

list.UpdateList(2, 60);

94
cout << "List after updating by adding 60 at index 2: ";

list.Display();

list.UpdateList(0, 5);

cout << "List after adding 5 at the beginning: ";

list.Display();

return 0;

Result:

95
Lab Manual #06 (Linear & Binary Searching, Bubble sorting)

Q1. Write a c++ code for linear searching.

Code:

#include <iostream>

using namespace std;

int linearSearch(int arr[], int n, int target) {

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

if (arr[i] == target) {

return i;

return -1;

int main() {

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};

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

int target;

cout << "Enter the target element: ";

cin >> target;

int result = linearSearch(arr, n, target);

if (result != -1) {

96
cout << "Target element found at index " << result << endl;

} else {

cout << "Target element not found in the array" << endl;

return 0;

Results:

Q2. Write a c++ code for binary searching.

Code:

#include <iostream>

using namespace std;

int binarySearch(int arr[], int n, int target) {

97
int left = 0;

int right = n - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (arr[mid] == target) {

return mid;

} else if (arr[mid] < target) {

left = mid + 1;

} else {

right = mid - 1;

return -1;

int main() {

int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};

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

int target;

cout << "Enter the target element: ";

cin >> target;

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

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

if (arr[i] > arr[j]) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

int result = binarySearch(arr, n, target);

if (result != -1) {

cout << "Target element found at index " << result << endl;

} else {

cout << "Target element not found in the array" << endl;

return 0;

Result:

99
Q3. Write c++ code for bubble sorting.

Code:

#include <iostream>

using namespace std;

void bubbleSort(int arr[], int n) {

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

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

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

100
arr[j + 1] = temp;

void printArray(int arr[], int n) {

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

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

cout << endl;

int main() {

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

int arr[] = {64, 34, 25, 12, 22, 11, 90};

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

cout << "Original array: ";

printArray(arr, n);

bubbleSort(arr, n);

cout << "Sorted array: ";

101
printArray(arr, n);

return 0;

Result:

Q4: Write the code for linear searching that returns any duplicate values and counts how many times
they appear in an array.

Code:

#include <iostream>

using namespace std;

void linearSearch(int arr[], int n) {

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

int count = 1;

102
for (int j = i + 1; j < n; j++) {

if (arr[i] == arr[j]) {

count++;

arr[j] = -1;

if (count > 1) {

cout << "Duplicate value: " << arr[i] << " appears " << count << " times." << endl;

int main() {

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

int arr[] = {2, 5, 8, 2, 5, 12, 8, 8, 91};

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

cout << "Original array: ";

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

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

cout << endl;

linearSearch(arr, n);

103
return 0;

Q5: Write the code for binary searching that dynamically sorts the data using a sorting algorithm.

Code:

#include <iostream>

using namespace std;

void bubbleSort(int arr[], int n) {

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

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

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

104
arr[j] = arr[j + 1];

arr[j + 1] = temp;

int binarySearch(int arr[], int n, int target) {

int left = 0;

int right = n - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (arr[mid] == target) {

return mid; // Return the index of the target element

} else if (arr[mid] < target) {

left = mid + 1;

} else {

right = mid - 1;

return -1; // Return -1 if the target element is not found

int main() {

105
int n;

cout << "Enter the number of elements: ";

cin >> n;

int* arr = new int[n];

cout << "Enter the elements: ";

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

cin >> arr[i];

// Sort the array using bubble sort

bubbleSort(arr, n);

cout << "Sorted array: ";

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

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

cout << endl;

int target;

cout << "Enter the target element: ";

cin >> target;

int result = binarySearch(arr, n, target);

106
if (result != -1) {

cout << "Target element found at index " << result << endl;

} else {

cout << "Target element not found" << endl;

delete[] arr;

return 0;

Result:

Q6: Implement bubble sort in descending order. The data should consist of the individual characters of
your name.

Code:

#include <iostream>

using namespace std;

107
void bubbleSort(char arr[], int n) {

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

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

if (arr[j] < arr[j + 1]) {

char temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

int main() {

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

char name[] = "Ibrahim Iqbal";

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

cout << "Original name: " << name << endl;

bubbleSort(name, n - 1);

cout << "Name in descending order: " << name << endl;

108
return 0;

Result:

Q7: Implement linear searching, binary searching, and bubble sorting in a real-time scenario, such as
searching for a product in a list or sorting a list of students by grades.

Code:

#include <iostream>

#include <string>

using namespace std;

struct Product {

string name;

int price;

};

109
int linearSearch(Product products[], int n, string targetName) {

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

if (products[i].name == targetName) {

return i;

return -1;

int binarySearch(Product products[], int n, string targetName) {

int left = 0;

int right = n - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (products[mid].name == targetName) {

return mid;

} else if (products[mid].name < targetName) {

left = mid + 1;

} else {

right = mid - 1;

110
return -1;

void bubbleSort(Product products[], int n) {

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

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

if (products[j].price > products[j + 1].price) {

Product temp = products[j];

products[j] = products[j + 1];

products[j + 1] = temp;

int main() {

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

Product products[] = {

{"Product A", 100},

{"Product B", 200},

{"Product C", 50},

{"Product D", 150},

{"Product E", 250}

111
};

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

string targetName = "Product C";

int index = linearSearch(products, n, targetName);

if (index != -1) {

cout << "Product found at index " << index << endl;

} else {

cout << "Product not found" << endl;

index = binarySearch(products, n, targetName);

if (index != -1) {

cout << "Product found at index " << index << endl;

} else {

cout << "Product not found" << endl;

bubbleSort(products, n);

cout << "Sorted list of products:" << endl;

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

cout << products[i].name << ": $" << products[i].price << endl;

112
return 0;

Result:

Q8: Create a C++ program where you simulate the stock prices of a company, and use linear search to
find a particular price, binary search to find prices within a range, and bubble sort to arrange the prices
in ascending or descending order.

Code:

#include <iostream>

using namespace std;

const int MAX_PRICES = 10;

void generatePrices(int prices[]) {

113
for (int i = 0; i < MAX_PRICES; i++) {

prices[i] = (i * 10) + (rand() % 10);

void printPrices(int prices[]) {

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

cout << "Day " << (i + 1) << ": $" << prices[i] << endl;

int linearSearch(int prices[], int targetPrice) {

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

if (prices[i] == targetPrice) {

return i;

return -1;

void binarySearch(int prices[], int minPrice, int maxPrice) {

int left = 0;

int right = MAX_PRICES - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

114
if (prices[mid] >= minPrice && prices[mid] <= maxPrice) {

cout << "Price $" << prices[mid] << " found within the range." << endl;

left = mid + 1;

} else if (prices[mid] < minPrice) {

left = mid + 1;

} else {

right = mid - 1;

void bubbleSort(int prices[], bool ascending) {

for (int i = 0; i < MAX_PRICES - 1; i++) {

for (int j = 0; j < MAX_PRICES - i - 1; j++) {

if ((ascending && prices[j] > prices[j + 1]) ||

(!ascending && prices[j] < prices[j + 1])) {

int temp = prices[j];

prices[j] = prices[j + 1];

prices[j + 1] = temp;

int main() {

115
cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

int stockPrices[MAX_PRICES];

srand(time(0));

generatePrices(stockPrices);

cout << "Original Stock Prices:" << endl;

printPrices(stockPrices);

int targetPrice = 50;

int index = linearSearch(stockPrices, targetPrice);

if (index != -1) {

cout << "Target price $" << targetPrice << " found on day " << (index + 1) << endl;

} else {

cout << "Target price $" << targetPrice << " not found" << endl;

int minPrice = 40;

int maxPrice = 60;

cout << "Prices within the range $" << minPrice << " to $" << maxPrice << ":" << endl;

bubbleSort(stockPrices, true);

binarySearch(stockPrices, minPrice, maxPrice);

116
cout << "Stock Prices in Ascending Order:" << endl;

bubbleSort(stockPrices, true);

printPrices(stockPrices);

cout << "Stock Prices in Descending Order:" << endl;

bubbleSort(stockPrices, false);

printPrices(stockPrices);

return 0;

117
Lab Manual #7

Q1. Perform the following for Stack Implementation using Linked list:

1. Push Operation

2. Pop Operation

3. Peek Operation (displays first, last and middle node)

4. Search Operation

5. Remove Operation

6. No push for duplicate value

Code:

#include <iostream>

using namespace std;

class node{

public:

int data;

node* next;

node(int val){

data=val;

next=NULL;

};

class stack{

public:

node* top;

int size;

118
stack(){

cout<<"Ibrahim Iqbal"<<endl;

cout<<"23018020022"<<endl;

top=NULL;

size=0;

void push(int a){

node* newnode=new node(a);

if(top==NULL){

top=newnode;

size++;

return;

}else{

node* temp=top;

while(temp!=NULL){

if(a==temp->data){

cout<<"Value already present. Try again with another


value."<<endl;

return;

temp=temp->next;

newnode->next=top;

top=newnode;

size++;

return;

119
}

void pop(){

if(size==0){

cout<<"The stack is empty."<<endl;

return;

}else{

cout<<"The popped value is: "<<top->data<<endl;

top=top->next;

size--;

return;

void peek(){

if(size==0){

cout<<"The stack is empty."<<endl;

return;

}else{

cout<<"The first value is: "<<top->data<<endl;

int mid=size/2;

int n;

node* temp=top;

while(n!=mid){

temp=temp->next;

n++;

120
}

cout<<"The middle value is: "<<temp->data<<endl;

while(temp->next!=NULL){

temp=temp->next;

cout<<"The last value is: "<<temp->data<<endl;

return;

void search(int b){

int index=0;

node* temp=top;

while(temp!=NULL){

if(b==temp->data){

cout<<"The value "<<b<<" is present at index "<<index<<endl;

temp=temp->next;

index++;

void remove(){

if(size==0){

cout<<"Stack is already empty."<<endl;

return;

}else{

121
cout<<"All values in stack have been deleted."<<endl;

delete top;

top=NULL;

size=0;

return;

void display(){

if(size==0){

cout<<"The stack is empty."<<endl;

return;

}else{

node* temp=top;

while(temp!=NULL){

cout<<temp->data<<endl;

temp=temp->next;

};

int main(){

stack obj;

obj.push(45);

obj.push(34);

obj.push(82);

122
obj.push(8);

obj.display();

obj.push(82);

obj.pop();

obj.display();

obj.peek();

obj.search(82);

obj.remove();

obj.display();

Result:

Q2. Perform the following for Queue Implementation using Linked list:

1. Enqueue Operation

123
2. Dequeue Operation

3. Peek Operation (displays first, last and middle node)

4. Search Operation

5. Remove Operation

6. No enqueue for duplicate value

Code:

#include <iostream>

using namespace std;

class node{

public:

int data;

node* next;

node(int val){

data=val;

next=NULL;

};

class queue{

public:

node* front;

node* rear;

int size;

queue(){

cout<<"Ibrahim Iqbal"<<endl;

124
cout<<"23018020022"<<endl;

front=NULL;

rear=NULL;

size=0;

void enqueue(int a){

node* newnode=new node(a);

if(front==NULL && rear==NULL){

front=rear=newnode;

size++;

return;

}else{

node* temp=front;

while(temp!=NULL){

if(a==temp->data){

cout<<"Value already present. Try again with another


value."<<endl;

return;

temp=temp->next;

rear->next=newnode;

rear=newnode;

size++;

return;

125
}

void dequeue(){

if(size==0){

cout<<"The queue is empty."<<endl;

return;

}else{

cout<<"The dequeued value is: "<<front->data<<endl;

front=front->next;

size--;

return;

void peek(){

if(size==0){

cout<<"The queue is empty."<<endl;

return;

}else{

cout<<"The first value is: "<<front->data<<endl;

int mid=size/2;

int n;

node* temp=front;

while(n!=mid){

temp=temp->next;

n++;

126
cout<<"The middle value is: "<<temp->data<<endl;

cout<<"The last value is: "<<rear->data<<endl;

return;

void search(int b){

int index=0;

node* temp=front;

while(temp!=NULL){

if(b==temp->data){

cout<<"The value "<<b<<" is present at index "<<index<<endl;

temp=temp->next;

index++;

void remove(){

if(size==0){

cout<<"Queue is already empty."<<endl;

return;

}else{

cout<<"All values in queue have been deleted."<<endl;

delete front;

delete rear;

front=NULL;

127
rear=NULL;

size=0;

return;

void display(){

if(size==0){

cout<<"The Queue is empty."<<endl;

return;

}else{

node* temp=front;

while(temp!=NULL){

cout<<temp->data<<endl;

temp=temp->next;

};

int main(){

queue obj;

obj.enqueue(45);

obj.enqueue(34);

obj.enqueue(82);

obj.enqueue(8);

obj.display();

128
obj.enqueue(82);

obj.dequeue();

obj.display();

obj.peek();

obj.search(82);

obj.remove();

obj.display();

Result:

Q3. Identify and implement the appropriate data structure(s) for the given scenarios (with minimum 3
attributes of respective scenario):

1. Restaurant Order Processing.

Code:

#include <iostream>

129
#include <cstring>

using namespace std;

class node{

public:

string data;

node* next;

node(string val){

data=val;

next=NULL;

};

class orders{

public:

node* front;

node* rear;

int size;

orders(){

cout<<"Welcome to Freddy Fazbear's Pizza.'"<<endl;

cout<<"Owned by Ibrahim Iqbal(23018020022)"<<endl;

front=NULL;

rear=NULL;

size=0;

void enqueue(string a){

130
node* newnode=new node(a);

if(front==NULL && rear==NULL){

front=rear=newnode;

size++;

return;

}else{

node* temp=front;

while(temp!=NULL){

if(a==temp->data){

cout<<"Order is already being prepared. Please input a


new order."<<endl;

return;

temp=temp->next;

rear->next=newnode;

rear=newnode;

size++;

return;

void dequeue(){

if(size==0){

cout<<"The order list is currently empty."<<endl;

return;

}else{

131
cout<<"Order prepared and delivered is: "<<front->data<<endl;

front=front->next;

size--;

return;

void peek(){

if(size==0){

cout<<"The order list is currently empty."<<endl;

return;

}else{

cout<<"Top priority order to deliver at the moment is: "<<front-


>data<<endl;

int mid=size/2;

int n;

node* temp=front;

while(n!=mid){

temp=temp->next;

n++;

cout<<"Order in the middle is: "<<temp->data<<endl;

cout<<"Order at the last of the list is: "<<rear->data<<endl;

return;

void search(string b){

132
int index=1;

node* temp=front;

while(temp!=NULL){

if(b==temp->data){

cout<<"The order "<<b<<" is at the queue number


"<<index<<endl;

temp=temp->next;

index++;

void remove(){

if(size==0){

cout<<"Order list is already empty."<<endl;

return;

}else{

cout<<"All orders in list have been removed."<<endl;

delete front;

delete rear;

front=NULL;

rear=NULL;

size=0;

return;

void display(){

133
if(size==0){

cout<<"The order list is currently empty."<<endl;

return;

}else{

cout<<"Orders in queue:"<<endl;

node* temp=front;

while(temp!=NULL){

cout<<temp->data<<endl;

temp=temp->next;

};

int main(){

orders obj;

cout<<"Pizzeria's ordering list:"<<endl;

cout<<endl;

obj.enqueue("1x large fajita pizza + 1x medium fries + 1x 1.5L drink : Table #11");

obj.enqueue("3x small peproni pizza + 3x 6 wings meal + 3x 250ml drink : Table #04");

obj.enqueue("1x lasagna meal + 1x lava cake + 1x 250ml drink : Table #09");

obj.enqueue("1x family meal no.4 + 5x fudge brownie + 6x chef's special sauce : Table #02");

obj.display();

cout<<endl;

obj.enqueue("1x large fajita pizza + 1x medium fries + 1x 1.5L drink : Table #11");

cout<<endl;

134
obj.dequeue();

cout<<endl;

obj.display();

cout<<endl;

obj.peek();

cout<<endl;

obj.search("1x lasagna meal + 1x lava cake + 1x 250ml drink : Table #09");

cout<<endl;

obj.remove();

obj.display();

Result:

135
2. Priority Task Manager: Design a task manager where high-priority tasks are processed using a
stack, and low-priority tasks are processed using a queue. Write a single code implementation
that manages transitions between the two priorities.

Code:
#include <iostream>
#include <string>
using namespace std;

class TaskNode {
public:
string task;
TaskNode* next;

TaskNode(string t){
task=t;
next=NULL;
}
};

class Stack {
private:
TaskNode* top;

public:
Stack(){
top=NULL;
}
void push(const string& task) {
TaskNode* newNode = new TaskNode(task);
newNode->next = top;
top = newNode;
}
string pop() {
if (top == NULL) {
cout << "Stack is empty!" << endl;
return "";
}
TaskNode* temp = top;
string task = temp->task;
top = top->next;

136
delete temp;
return task;
}
bool isEmpty() {
return top == NULL;
}

string peek() {
if (top == nullptr) return "";
return top->task;
}
};
class Queue {
private:
TaskNode* front;
TaskNode* rear;

public:
Queue(){
front=NULL;
rear=NULL;
}

void enqueue(const string& task) {


TaskNode* newNode = new TaskNode(task);
if (rear == nullptr) {
front = rear = newNode;
return;
}
rear->next = newNode;
rear = newNode;
}

string dequeue() {
if (front == nullptr) {
cout << "Queue is empty!" << endl;
return "";
}
TaskNode* temp = front;
string task = temp->task;
front = front->next;

137
if (front == nullptr) {
rear = nullptr;
}
delete temp;
return task;
}

bool isEmpty() {
return front == nullptr;
}

string peek() {
if (front == nullptr) return "";
return front->task;
}
};

class TaskManager {
private:
Stack highPriorityStack;
Queue lowPriorityQueue;

public:
TaskManager(){
cout<<"Ibrahim Iqbal"<<endl;
cout<<"23018020022"<<endl;
}

void addHighPriorityTask(const string& task) {


highPriorityStack.push(task);
}

void addLowPriorityTask(const string& task) {


lowPriorityQueue.enqueue(task);
}

void processHighPriorityTask() {
if (!highPriorityStack.isEmpty()) {
cout << "Processing high-priority task: " << highPriorityStack.pop() << endl;
} else {

138
cout << "No high-priority tasks to process!" << endl;
}
}

void processLowPriorityTask() {
if (!lowPriorityQueue.isEmpty()) {
cout << "Processing low-priority task: " << lowPriorityQueue.dequeue() << endl;
} else {
cout << "No low-priority tasks to process!" << endl;
}
}
void moveTaskToHighPriority() {
if (!lowPriorityQueue.isEmpty()) {
string task = lowPriorityQueue.dequeue();
highPriorityStack.push(task);
cout << "Moved task to high-priority: " << task << endl;
} else {
cout << "No tasks in the low-priority queue to move!" << endl;
}
}

void moveTaskToLowPriority() {
if (!highPriorityStack.isEmpty()) {
string task = highPriorityStack.pop();
lowPriorityQueue.enqueue(task);
cout << "Moved task to low-priority: " << task << endl;
} else {
cout << "No tasks in the high-priority stack to move!" << endl;
}
}

void displayTasks() {
cout << "High-priority task (stack top): " << highPriorityStack.peek() << endl;
cout << "Low-priority task (queue front): " << lowPriorityQueue.peek() << endl;
}
};

int main() {
TaskManager taskManager;

139
taskManager.addHighPriorityTask("Finish project report");
taskManager.addLowPriorityTask("Clean the desk");
taskManager.addLowPriorityTask("Respond to emails");
taskManager.displayTasks();

taskManager.processHighPriorityTask();
taskManager.processLowPriorityTask();

taskManager.moveTaskToLowPriority();
taskManager.moveTaskToHighPriority();

taskManager.displayTasks();

return 0;
}
Result:

140

You might also like