Lab Task 5
Lab Task 5
23108189
Lab Task 6
Code:
#include <iostream>
class Stack {
public:
struct Student {
int id;
string name;
};
private:
Student arr[100];
int top;
public:
Stack() {
top = -1;
}
bool isEmpty() {
return (top == -1);
}
bool isFull() {
return (top == 99);
}
void push(Student s) {
if (isFull()) {
cout << "Error: Stack Overflow" << endl;
return;
}
arr[++top] = s;
}
Student pop() {
if (isEmpty()) {
cout << "Error: Stack Underflow" << endl;
Student s = {-1, ""};
return s;
}
return arr[top--];
}
Student peek() {
if (isEmpty()) {
cout << "Error: Stack Underflow" << endl;
Student s = {-1, ""};
return s;
}
return arr[top];
}
void display() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return;
}
cout << "Stack elements: " << endl;
for (int i = top; i >= 0; i--) {
cout << "ID: " << arr[i].id << ", Name: " << arr[i].name << endl;
}
}
};
int main() {
Stack s;
s.display();
s.pop();
s.pop();
s.display();
return 0;
}
Output
______________________________
Code
#include <iostream>
class Stack {
public:
struct Student {
int id;
string name;
};
private:
struct Node {
Student data;
Node* next;
};
Node* top;
public:
Stack() : top(NULL) {}
~Stack() {
while (!isEmpty()) {
pop();
}
}
bool isEmpty() {
return (top == NULL);
}
void push(Student s) {
Node* newNode = new Node;
newNode->data = s;
newNode->next = top;
top = newNode;
}
Student pop() {
if (isEmpty()) {
cout << "Error: Stack Underflow" << endl;
return {-1, ""};
}
Node* temp = top;
Student poppedData = top->data;
top = top->next;
delete temp;
return poppedData;
}
Student peek() {
if (isEmpty()) {
cout << "Error: Stack Underflow" << endl;
return {-1, ""};
}
return top->data;
}
void display() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return;
}
Node* current = top;
cout << "Stack elements: " << endl;
while (current != NULL) {
cout << "ID: " << current->data.id << ", Name: " << current->data.name << endl;
current = current->next;
}
}
};
int main() {
Stack s;
s.push({101, "Student 1"});
s.push({102, "Student 2"});
s.push({103, "Student 3"});
s.push({104, "Student 4"});
s.push({105, "Student 5"});
s.display();
s.pop();
s.pop();
s.display();
return 0;
}
OUTPUT
_________________________________________