0% found this document useful (0 votes)
26 views43 pages

Dsa Lab Manual

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)
26 views43 pages

Dsa Lab Manual

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/ 43

DATA STRUCTURES AND

ALGORITHMS LAB

LAB MANUAL
YASHALL FALLAK
BSCS BATCH 18
BSCS 07
LAB INSTRUCTOR: JAVERIA JALIL
KNOWLEDGE UNIT OF SYSTEMS AND
TECHNOLOGY
UMT SIALKOT
Contents
QUESTION#1.............................................................................................................. 2
INPUT:..................................................................................................................... 3
OUTPUT:.................................................................................................................. 9
QUESTION#2......................................................................................................... 14
INPUT:................................................................................................................... 14
OUTPUT:................................................................................................................ 18
QUESTION #3........................................................................................................ 21
INPUT:................................................................................................................... 22
OUTPUT:................................................................................................................ 24
QUESTION #4........................................................................................................... 24
INPUT:................................................................................................................... 24
OUTPUT:................................................................................................................ 29
QUESTION#1............................................................................................................ 32
INPUT:................................................................................................................... 32
OUTPUT:................................................................................................................ 35
QUESTION #2........................................................................................................... 36
INPUT:................................................................................................................... 36
OUTPUT:................................................................................................................ 39
QUESTION #3........................................................................................................... 40
INPUT:................................................................................................................... 40
OUTPUT:................................................................................................................ 44

MANUAL #1
QUESTION#1
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.

• min Val(): Displays Minimum value item in stack.

• max Val(): Displays Maximum value item in stack.

INPUT:
#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

class Stack {

private:

static const int capacity = 100;

int arr[capacity];

int top;

public:

Stack() : top(-1) {}

void push(int item) {

if (top >= capacity - 1) {

cout << "Stack Overflow\n";

return;

}
arr[++top] = item;

cout << item << " pushed onto stack.\n";

int pop() {

if (top < 0) {

cout << "Stack Underflow\n";

return -1;

return arr[top--];

void traverse() const {

if (top < 0) {

cout << "Stack is empty\n";

return;

cout << "Stack items: ";

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

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

cout << endl;

void sort(bool ascending = true) {

if (top < 0) {

cout << "Stack is empty, cannot sort\n";

return;
}

std::sort(arr, arr + top + 1);

if (!ascending) {

std::reverse(arr, arr + top + 1);

cout << "Stack sorted.\n";

void search(int item) const {

vector<int> indexes;

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

if (arr[i] == item) {

indexes.push_back(i);

if (!indexes.empty()) {

cout << "Value " << item << " found at index(es): ";

for (int index : indexes) {

cout << index << " ";

cout << endl;

} else {

cout << "Value " << item << " not found in stack.\n";

void minVal() const {


if (top < 0) {

cout << "Stack is empty\n";

return;

int minValue = arr[0];

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

if (arr[i] < minValue) {

minValue = arr[i];

cout << "Minimum value in stack: " << minValue << endl;

void maxVal() const {

if (top < 0) {

cout << "Stack is empty\n";

return;

int maxValue = arr[0];

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

if (arr[i] > maxValue) {

maxValue = arr[i];

cout << "Maximum value in stack: " << maxValue << endl;

};
int main() {

Stack stack;

int choice, value;

do {

cout << "\n---------------------Stack Menu:----------------------\n";

cout << "1. Push\n";

cout << "2. Pop\n";

cout << "3. Traverse\n";

cout << "4. Sort (Ascending)\n";

cout << "5. Sort (Descending)\n";

cout << "6. Search\n";

cout << "7. Minimum Value\n";

cout << "8. Maximum Value\n";

cout << "9. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1:

cout << "Enter value to push: ";

cin >> value;

stack.push(value);

break;

case 2:

cout << "Popped item: " << stack.pop() << endl;

break;

case 3:
stack.traverse();

break;

case 4:

stack.sort(true);

break;

case 5:

stack.sort(false);

break;

case 6:

cout << "Enter value to search: ";

cin >> value;

stack.search(value);

break;

case 7:

stack.minVal();

break;

case 8:

stack.maxVal();

break;

case 9:

cout << "Exiting...\n";

break;

default:

cout << "Invalid choice. Please try again.\n";

} while (choice != 9);

return 0;
}

OUTPUT:
OPTION 1
OPTION 2

OPTION 3

OPTION 4
OPTION 5

OPTION 6

OPTION 7 AND 8
OPTION 9
QUESTION#2
2. Write a function to identify and display any duplicate data in the
stack along with their indices.

INPUT:
#include <iostream>

#include <unordered_map>

#include <vector>

using namespace std;

class Stack {

private:

static const int capacity = 100;

int arr[capacity];

int top;

public:

Stack() : top(-1) {}

void push(int item) {

if (top >= capacity - 1) {

cout << "Stack Overflow\n";

return;

arr[++top] = item;

cout << item << " pushed onto stack.\n";

}
int pop() {

if (top < 0) {

cout << "Stack Underflow\n";

return -1;

return arr[top--];

void traverse() const {

if (top < 0) {

cout << "Stack is empty\n";

return;

cout << "Stack items: ";

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

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

cout << endl;

void findDuplicates() const {

unordered_map<int, vector<int>> indices;

// Record the indices for each value

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

indices[arr[i]].push_back(i);

}
bool hasDuplicates = false;

for (const auto& entry : indices) {

if (entry.second.size() > 1) {

hasDuplicates = true;

cout << "Value " << entry.first << " found at indices: ";

for (int index : entry.second) {

cout << index << " ";

cout << endl;

if (!hasDuplicates) {

cout << "No duplicates found.\n";

};

int main() {

Stack stack;

int choice, value;

do {

cout << "\nStack Menu:\n";

cout << "1. Push\n";

cout << "2. Pop\n";

cout << "3. Traverse\n";

cout << "4. Find Duplicates\n";


cout << "5. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1:

cout << "Enter value to push: ";

cin >> value;

stack.push(value);

break;

case 2:

cout << "Popped item: " << stack.pop() << endl;

break;

case 3:

stack.traverse();

break;

case 4:

stack.findDuplicates();

break;

case 5:

cout << "Exiting...\n";

break;

default:

cout << "Invalid choice. Please try again.\n";

} while (choice != 5);

return 0;
}

OUTPUT:
OPTION 1
OPTION 2
OPTION 3

OPTION 4
OPTION 5

QUESTION #3
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.

INPUT:
#include <iostream>

#include <stack>

#include <vector>

#include <algorithm>

using namespace std;

void displayStack(stack<int> s) {

cout << "Stack contents (top to bottom): ";

while (!s.empty()) {

cout << s.top() << " ";

s.pop();

cout << endl;

int main() {

stack<int> inputStack;

stack<int> sortedStack;

vector<int> elements;

int n, value;

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

cin >> n;
cout << "Enter " << n << " elements:\n";

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

cin >> value;

inputStack.push(value);

elements.push_back(value);

sort(elements.begin(), elements.end());

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

sortedStack.push(elements[i]);

cout << "\nInput Stack:\n";

displayStack(inputStack);

cout << "Sorted Stack:\n";

displayStack(sortedStack);

return 0;

}
OUTPUT:

QUESTION #4
4. Write a C++ program that simulates three real-world scenarios
where stacks are useful. Implement each scenario using stack
operations.

INPUT:
#include <iostream>

#include <stack>

#include <string>

using namespace std;

void plateStack() {

stack<string> plates;

string command, plate;


while (true) {

cout << "\nPlate Stack - Enter 'add <plate>', 'remove', or 'exit': ";

getline(cin, command);

if (command == "exit") break;

if (command.substr(0, 4) == "add ") {

plate = command.substr(4);

plates.push(plate);

cout << "Added plate: " << plate << endl;

} else if (command == "remove") {

if (!plates.empty()) {

cout << "Removed plate: " << plates.top() << endl;

plates.pop();

} else {

cout << "No plates to remove." << endl;

} else {

cout << "Invalid command." << endl;

void browserHistory() {

stack<string> history;
string url, command;

while (true) {

cout << "\nBrowser History - Enter a URL, 'back', or 'exit': ";

getline(cin, command);

if (command == "exit") break;

if (command == "back") {

if (!history.empty()) {

cout << "Going back to: " << history.top() << endl;

history.pop();

} else {

cout << "No more history to go back to." << endl;

} else {

history.push(command);

cout << "Visited: " << command << endl;

void undoFunction() {

stack<string> actions;

string command;
while (true) {

cout << "\nUndo Function - Enter an action or 'undo', or 'exit': ";

getline(cin, command);

if (command == "exit") break;

if (command == "undo") {

if (!actions.empty()) {

cout << "Undid action: " << actions.top() << endl;

actions.pop();

} else {

cout << "No actions to undo." << endl;

} else {

actions.push(command);

cout << "Performed action: " << command << endl;

int main() {

int choice;

while (true) {

cout << "\nChoose a scenario:\n";

cout << "1. Stack of Plates\n";


cout << "2. Browser History\n";

cout << "3. Undo Function\n";

cout << "4. Exit\n";

cout << "Enter your choice (1-4): ";

cin >> choice;

cin.ignore(); // To ignore the newline character left in the input buffer

switch (choice) {

case 1:

plateStack();

break;

case 2:

browserHistory();

break;

case 3:

undoFunction();

break;

case 4:

cout << "Exiting the program." << endl;

return 0;

default:

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

return 0;
}

OUTPUT:
OPTION 1

OPTION 2

OPTION 3
OPTION 4

THE END!
MANUAL #2
QUESTION#1
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.
INPUT:
#include <iostream>

#include <stack>

using namespace std;

int prec(char c) {

if (c == '^') return 3;

if (c == '*' || c == '/') return 2;

if (c == '+' || c == '-') return 1;

return -1;

bool areParenthesesBalanced(const string& s) {

stack<char> st;

for (char c : s) {

if (c == '(') {

st.push(c);

} else if (c == ')') {

if (st.empty()) return false;


st.pop();

return st.empty();

string infixtopostfix(string s) {

stack<char> st;

string res;

for (int i = 0; i < s.length(); i++) {

if (isalpha(s[i])) {

res += s[i];

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

st.push(s[i]);

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

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

res += st.top();

st.pop();

if (!st.empty()) {

st.pop();

} else {

while (!st.empty() && prec(st.top()) >= prec(s[i])) {

res += st.top();
st.pop();

st.push(s[i]);

while (!st.empty()) {

res += st.top();

st.pop();

return res;

int main() {

string expression;

char choice;

do {

cout << "Enter an infix expression: ";

getline(cin, expression);

if (!areParenthesesBalanced(expression)) {

cout << "Error: The expression contains unbalanced parentheses." << endl;

} else {

string postfix = infixtopostfix(expression);


cout << "Postfix expression: " << postfix << endl;

cout << "Do you want to convert another expression? (y/n): ";

cin >> choice;

cin.ignore();

} while (choice == 'y' || choice == 'Y');

return 0;

OUTPUT:
DISPLAYING ERROR IF PARANTHESIS ARE UNBALANCED

DISPLAYING OUTPUT EHEN PARANTHESIS ARE BALANCED


QUESTION #2
2.Write C++ program to convert infix expression
to a prefix expression using a stack.
INPUT:
#include <iostream>

#include <stack>

#include <algorithm>

using namespace std;

int prec(char c) {

if (c == '^') return 3;

if (c == '*' || c == '/') return 2;

if (c == '+' || c == '-') return 1;

return -1;

bool areParenthesesBalanced(const string& s) {

stack<char> st;

for (char c : s) {

if (c == '(') {

st.push(c);

} else if (c == ')') {

if (st.empty()) return false;

st.pop();
}

return st.empty();

string infixtoprefix(string s) {

reverse(s.begin(), s.end());

stack<char> st;

string res;

for (int i = 0; i < s.length(); i++) {

if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {

res += s[i];

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

st.push(s[i]);

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

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

res += st.top();

st.pop();

if (!st.empty()) {

st.pop(); // Remove the ')' from the stack

} else {

while (!st.empty() && prec(st.top()) >= prec(s[i])) {

res += st.top();
st.pop();

st.push(s[i]);

while (!st.empty()) {

res += st.top();

st.pop();

reverse(res.begin(), res.end());

return res;

int main() {

string expression;

char choice;

do {

cout << "Enter an infix expression: ";

getline(cin, expression);

if (!areParenthesesBalanced(expression)) {

cout << "Error: The expression contains unbalanced parentheses." << endl;

} else {
string prefix = infixtoprefix(expression);

cout << "Prefix expression: " << prefix << endl;

cout << "Do you want to convert another expression? (y/n): ";

cin >> choice;

cin.ignore();

} while (choice == 'y' || choice == 'Y');

return 0;

OUTPUT:
DISPLAYING ERROR AS THE PARANTHESIS ARE UNBALANCED

DISPLAYING OUTPUT AS PARANTHESIS ARE BALANCED


QUESTION #3
3.Implement the given operator precedence
table in the conversion of an infix expression
to a prefix expression.

INPUT:
#include <iostream>

#include <stack>

#include <algorithm>

using namespace std;

int prec(char c) {

if (c == '!') return 1;

if (c == '(' || c == ')') return 2;

if (c == '*' || c == '/' || c == '%') return 3;

if (c == '+' || c == '-') return 4;

if (c == '>' || c == '<' || c == '=' || c == '>=' || c == '<=') return 5;

return -1;

bool areParenthesesBalanced(const string& s) {

stack<char> st;
for (char c : s) {

if (c == '(') {

st.push(c);

} else if (c == ')') {

if (st.empty()) return false;

st.pop();

return st.empty();

string infixtoprefix(string s) {

reverse(s.begin(), s.end());

stack<char> st;

string res;

for (int i = 0; i < s.length(); i++) {

if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {

res += s[i];

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

st.push(s[i]);

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

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

res += st.top();

st.pop();

}
if (!st.empty()) {

st.pop();

} else {

while (!st.empty() && prec(st.top()) >= prec(s[i])) {

res += st.top();

st.pop();

st.push(s[i]);

while (!st.empty()) {

res += st.top();

st.pop();

reverse(res.begin(), res.end());

return res;

int main() {

string expression;

char choice;

do {
cout << "Enter an infix expression: ";

getline(cin, expression);

if (!areParenthesesBalanced(expression)) {

cout << "Error: The expression contains unbalanced parentheses." << endl;

} else {

string prefix = infixtoprefix(expression);

cout << "Prefix expression: " << prefix << endl;

cout << "Do you want to convert another expression? (y/n): ";

cin >> choice;

cin.ignore();

} while (choice == 'y' || choice == 'Y');

return 0;

OUTPUT:

THE END!

You might also like