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

Data Structure SHEET

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

Data Structure SHEET

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

‫كلية الحاسبات والمعلومات – جامعة طنطا‬

Faculty of Computers and Informatics – Tanta University

Practical Sheet
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

Student Name: ‫ﻣﺣﻣود ﺻﻼح اﻟﺳﯾد ﻣﺻطﻔﻰ دﺑﺎ‬

Section No: B11 NUM 27

Grade:
2023/2024 2023/2024 2023/2024

Signature:

١٦٨
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

1. Balancing Parentheses:
 Problem: Check if a given expression has balanced parentheses, brackets, and curly
braces. For example, determine if "{(A + B)}" is balanced.
 Example:
 Input: "{(A + B)}"
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Output: Balanced
#include <iostream>
#include <stack>
using namespace std;
bool isBalanced(const string& expression) {
stack<char> s;
for (char c : expression) {
switch (c) {
case '(':
case '{':
case '[':
s.push(c);
break;
case ')':
if (!s.empty() && s.top() == '(') {
s.pop();
} else {
2023/2024 return false; // unbalanced
2023/2024 2023/2024
}
break;
case '}':
if (!s.empty() && s.top() == '{') {
s.pop();
} else {
return false; // unbalanced
}
break;
case ']':
if (!s.empty() && s.top() == '[') {
s.pop();
} else {
return false; // unbalanced
}
break;
}
}
return s.empty();
}
int main() {
string expression;
cout << "Enter An Expression: ";
getline(cin, expression);
if (isBalanced(expression)) {
cout << "This Expression Is Balanced" << endl;
} else {
cout << "This Expression Is Unbalanced" << endl;
}
return 0;
}

١٦٩
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

2. Expression Evaluation:
 Problem: Convert an infix mathematical expression to postfix notation and evaluate
the result. For example, evaluate "3 * (4 + 2)".
 Example:
 Input: "3 * (4 + 2)"
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Output: 18
for (char c : postfix) {
#include <iostream> if (isdigit(c)) {
#include <stack> operands.push(c - '0');
#include <string> } else if (isOperator(c)) {
using namespace std; double operand2 = operands.top();
bool isOperator(char c) { operands.pop();
return c == '+' || c == '-' || c == '*' || c == '/'; double operand1 = operands.top();
} operands.pop();
int precedence(char c) { double result;
if (c == '+' || c == '-') { switch (c) {
return 1; case '+':
} else if (c == '*' || c == '/') { result = operand1 + operand2;
return 2; break;
} else { case '-':
return 0; result = operand1 - operand2;
} break;
} 2023/2024 2023/2024
case '*': 2023/2024
string infixToPostfix(string infix) { result = operand1 * operand2;
stack<char> operators; break;
string postfix; case '/':
for (char c : infix) { result = operand1 / operand2;
if (isalnum(c)) { break;
postfix += c; }
} else if (isOperator(c)) { operands.push(result);
while (!operators.empty() && precedence(operators.top()) }
>= precedence(c)) { }
postfix += operators.top(); if (operands.size() != 1) {
operators.pop(); throw invalid_argument("Invalid expression");
} }
operators.push(c); return operands.top();
} else if (c == '(') { }
operators.push(c); int main() {
} else if (c == ')') { string infixExpression;
while (!operators.empty() && operators.top() != '(') { cout << "Enter an infix expression: ";
postfix += operators.top(); getline(cin, infixExpression);
operators.pop(); string postfixExpression = infixToPostfix
} (infixExpression);
operators.pop(); cout << "Postfix expression: "
} else { << postfixExpression << endl;
throw invalid_argument("Invalid character in expression" double result = evaluatePostfix(postfixExpression)
); ;
} cout << "Result: " << result << endl;
} return 0;
while (!operators.empty()) { }
postfix += operators.top();
operators.pop();
}
return postfix;
}
double evaluatePostfix(string postfix) {
stack<double> operands;
١٧٠
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

3. Reversing a Linked List:


 Problem: Reverse a singly linked list. For example, reverse the linked list: 1 -> 2 -> 3
-> 4.
 Example:
 Input: 1 -> 2 -> 3 -> 4
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Output: 4 -> 3 -> 2 -> 1

#include <iostream>
using namespace std;

struct Node {
int data;
Node* next;
};
Node* reverseList(Node* head) {
Node* prev = nullptr;
Node* curr = head;
while (curr) {
Node* nextNode = curr->next;
2023/2024 2023/2024 2023/2024
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
void printList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
int main() {
Node* head = new Node{1};
head->next = new Node{2};
head->next->next = new Node{3};
head->next->next->next = new Node{4};
cout << "The Original List Is: ";
printList(head);

head = reverseList(head);
cout << "The Reversed List Is: ";
printList(head);
return 0;
} ١٧١
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

4. Queue-Based Breadth-First Search (BFS):


 Problem: Implement BFS using a queue to find the shortest path between two
nodes in a graph. For example, find the shortest path from node A to node F in a
graph.
 Example:
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Input: Graph with nodes A, B, C, D, E, F


 Output: Shortest path from A to F: A -> B -> E -> F
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;

unordered_map<char, vector<char>> graph;


vector<char> bfs(char start, char target) {
queue<char> q;
unordered_map<char, char> parent;
unordered_set<char> visited;
q.push(start);
visited.insert(start);

while (!q.empty()) {
char current = q.front();
q.pop();
2023/2024 2023/2024 2023/2024
if (current == target) {
break;
}
for (char neighbor : graph[current]) {
if (visited.count(neighbor) == 0) {
q.push(neighbor);
visited.insert(neighbor);
parent[neighbor] = current;
}
}
}
vector<char> path;
char current = target;
while (current != start) {
path.push_back(current);
current = parent[current];
}
path.push_back(start);

reverse(path.begin(), path.end());
return path;
}
int main() {
graph['A'] = {'B', 'C'};
graph['B'] = {'D', 'E'};
graph['C'] = {'F'};
graph['D'] = {};
graph['E'] = {'F'};
graph['F'] = {};

char start = 'A';


char target = 'F';
vector<char> shortestPath = bfs(start, target);

if (shortestPath.empty()) {
cout << "No path exists between " << start << " and " << target << endl;
} else {
cout << "Shortest path from " << start << " to " << target << " Is: ";
for (char node : shortestPath) {
cout << node << " -> ";
}
cout << "End" << endl;
}
return 0;
} ١٧٢
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

5. mplementing a To-Do List:


 Problem: Create a to-do list application using a list or array, allowing users to add,
remove, and mark tasks as complete. For example, add, remove, and mark tasks in a
to-do list.
 Example:
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

#include <iostream>  To-Do List:


#include <vector>
#include <string>
using namespace std;
1. Buy groceries
vector<string> toDoList;
2. Finish report
void displayToDoList() {
cout << "To-Do List:" << endl;
3. Exercise
for (int i = 0; i < toDoList.size(); i++) { 4. Call mom
cout << i + 1 << ". " << toDoList[i] << endl;
}
}
void addTask() {
string task;
cout << "Enter a task to add: ";
cin >> task;
getline(cin, task);
toDoList.push_back(task);
cout << "Task added successfully!" << endl;
}
void removeTask() {
int taskIndex;
cout << "Enter the number of the task to remove: ";
cin >> taskIndex;
2023/2024
if (taskIndex > 0 && taskIndex <= toDoList.size()) {
2023/2024 2023/2024
toDoList.erase(toDoList.begin() + taskIndex - 1);
cout << "Task removed successfully!" << endl;
} else {
cout << "Invalid task number." << endl;
}
}
void markTaskComplete() {
int taskIndex;
cout << "Enter the number of the task to mark as complete: ";
cin >> taskIndex;

if (taskIndex > 0 && taskIndex <= toDoList.size()) {


toDoList[taskIndex - 1] = "(Completed) " + toDoList[taskIndex - 1];
cout << "Task marked as complete!" << endl;
} else {
cout << "Invalid task number." << endl;
}
}
int main() {
int choice;
do {
cout << "\nTo-Do List Menu:" << endl;
cout << "1. Display To-Do List" << endl;
cout << "2. Add Task" << endl;
cout << "3. Remove Task" << endl;
cout << "4. Mark Task as Complete" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
displayToDoList();
break;
case 2:
addTask();
break;
case 3:
removeTask();
break;
case 4:
markTaskComplete();
break;
case 5:
cout << "Exiting..." << endl;
break;
default: ١٧٣
cout << "Invalid choice." << endl;
}
} while (choice != 5);
return 0;
}
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

6. Binary Search Tree (BST) Operations:


 Problem: Implement common BST operations like inserting a node, searching for a
value, and performing traversals. For example, create a BST and perform these
operations.
 Example:
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Insert values: 10, 5, 15, 2, 7


 Search for 7: Found
 In-order traversal: 2, 5, 7, 10, 15
#include <iostream>
using namespace std;

struct Node {
int data;
Node* left;
Node* right;

Node(int val) {
data = val;
left = right = nullptr;
}
};

Node* insert(Node* root, int val) {


if (root == nullptr) {
return new Node(val);
} 2023/2024 2023/2024 2023/2024
if (val < root->data) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}

return root;
}
bool search(Node* root, int val) {
if (root == nullptr) {
return false;
}
if (root->data == val) {
return true;
}
if (val < root->data) {
return search(root->left, val);
} else {
return search(root->right, val);
}
}
void inorderTraversal(Node* root) {
if (root != nullptr) {
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
}
int main() {
Node* root = nullptr;

root = insert(root, 10);


insert(root, 5);
insert(root, 15);
insert(root, 2);
insert(root, 7);
if (search(root, 7)) {
cout << "7 found in the BST\n";
} else {
cout << "7 not found in the BST\n";
}
cout << "In-order traversal: ";
inorderTraversal(root);
cout << endl; ١٧٤
return 0;
}
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

#include <iostream>
7. Stack-Based Undo/Redo Functionality:
#include <stack>
#include <string>
using namespace std; Problem: Design a text editor that uses a stack to implement undo and redo
stack<string> undoStack;
stack<string> redoStack;functionality for user actions. For example, type, delete, and undo/redo text in a text
editor.
string currentText = "";
void displayText() {

Example:
cout << "Current text: " << currentText << endl;
} 
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

User types: "Hello, World!"


void typeText(string text) {
undoStack.push(currentText);
User undoes: "Hello, "
currentText += text;
redoStack = stack<string>(); //Clear redo stack on new actions

}
displayText();
User redoes: "Hello, World!"

void deleteText() {
if (currentText.length() > 0) {
undoStack.push(currentText);
currentText.pop_back();
redoStack = stack<string>();
displayText();
} else {
cout << "Cannot delete: Text is empty." << endl;
}
}
void undo() {
if (!undoStack.empty()) {
redoStack.push(currentText);
currentText = undoStack.top();
undoStack.pop();
displayText();
} else {
cout << "Cannot
2023/2024undo: No more actions to undo." << endl; 2023/2024 2023/2024
}
}
void redo() {
if (!redoStack.empty()) {
undoStack.push(currentText);
currentText = redoStack.top();
redoStack.pop();
displayText();
} else {
cout << "Cannot redo: No more actions to redo." << endl;
}
}
int main() {
int choice;
do {
cout << "\nText Editor Menu:" << endl;
cout << "1. Type Text" << endl;
cout << "2. Delete Text" << endl;
cout << "3. Undo" << endl;
cout << "4. Redo" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1: {
string text;
cout << "Enter text to type: ";
cin >> text;
getline(cin, text);
typeText(text);
break;
}
case 2:
deleteText();
break;
case 3:
undo();
break;
case 4:
redo();
break;
case 5:
cout << "Exiting..." << endl;
break;
default: ١٧٥
cout << "Invalid choice." << endl;
}
} while (choice != 5);
return 0;
}
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

8. Queue for Task Scheduling:


 Problem: Create a task scheduler that uses a queue to manage and execute tasks in
the order they are added. For example, schedule and execute tasks.
 Example:
 Scheduled tasks: Task A, Task B, Task C
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Execution order: Task A -> Task B -> Task C


#include <iostream>
#include <queue>
#include <vector>
#include <string>
using namespace std;

class TaskScheduler {
public:
void addTask(const std::string& task);
void scheduleTasks();
void executeTask();

private:
queue<string> taskQueue;
vector<string> completedTasks;
};

void TaskScheduler::addTask(const string& task) {


2023/2024
taskQueue.push(task); 2023/2024 2023/2024
}

void TaskScheduler::scheduleTasks() {
cout << "Scheduled tasks: ";
while (!taskQueue.empty()) {
cout << taskQueue.front() << ", ";
completedTasks.push_back(taskQueue.front());
taskQueue.pop();
}
cout << "\n";
}

void TaskScheduler::executeTask() {
cout << "Execution order: ";
for (const auto& task : completedTasks) {
cout << task << " -> ";
}
cout << "\n";
}

int main() {
TaskScheduler scheduler;
scheduler.addTask("Task A");
scheduler.addTask("Task B");
scheduler.addTask("Task C");

scheduler.scheduleTasks();
scheduler.executeTask();

return 0;
}

١٧٦
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

9. Detecting a Cycle in a Linked List:


 Problem: Write a program to detect cycles in a linked list. For example, detect cycles
in the following linked list:
 Example:
 Linked List with a cycle: 1 -> 2 -> 3 -> 4 -> 2 (cycles back to 2)
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

#include <iostream>
using namespace std;

struct Node {
int data;
Node* next;
};

bool detectCycle(Node *head) {


Node *slow = head, *fast = head;
do {
if (!fast || !fast->next) return false; /
slow = slow->next;
fast = fast->next->next;
} while (slow != fast);
return true;

int main() {
2023/2024 2023/2024 2023/2024
Node *head = new Node{1, new Node{2, new Node{3, new Node{4, nullptr}}}};
head->next->next->next->next = head->next;

cout << (detectCycle(head) ? "Cycle detected!" : "No cycle.") << endl;

return 0;
}

١٧٧
‫كلية الحاسبات والمعلومات – جامعة طنطا‬
Faculty of Computers and Informatics – Tanta University

10. Construct a Binary Search Tree from Sorted Array:


 Problem: Given a sorted array, construct a balanced binary search tree. For example,
create a BST from the sorted array: [1, 2, 3, 4, 5, 6].
 Example:
 Input: [1, 2, 3, 4, 5, 6]
‫ﻣﺤﻤﻮﺩ ﺻﻼﺡ ﺍﻟﺴﻴﺪ ﻣﺼﻄﻔﻰ ﺩﺑﺎ‬

 Constructed BST: 3 /
25//
146
#include <iostream>
#include <queue>
using namespace std;

struct Node {
int data;
Node* left;
Node* right;

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

Node* sortedArrayToBST(int arr[], int start, int end) {


if (start > end) {
return nullptr;
2023/2024 2023/2024 2023/2024
}

int mid = start + (end - start) / 2;


Node* root = new Node(arr[mid]);

root->left = sortedArrayToBST(arr, start, mid - 1);


root->right = sortedArrayToBST(arr, mid + 1, end);

return root;
}

void printTree(Node* root) {


if (root == nullptr) {
return;
}

queue<Node*> q;
q.push(root);

while (!q.empty()) {
Node* temp = q.front();
q.pop();

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

if (temp->left != nullptr) {
q.push(temp->left);
}

if (temp->right != nullptr) {
q.push(temp->right);
}
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

Node* root = sortedArrayToBST(arr, 0, n - 1);

cout << "Constructed BST: ";


printTree(root);
cout << endl;
١٧٨
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy