Course objective Solve simple real-life problems requiring numerical skills Docu
ID: 3836869 • Letter: C
Question
Course objective Solve simple real-life problems requiring numerical skills Document programming projects Present programming projects Discuss major issues in programming and OOP specifically Project Description There are many Data structures used in computer science to store sequence of elements. Two such data structures that store and retrieve elements in some sequence are Stacks and Queues. A Stack is a list of elements in which any new element is inserted at the top of the list, which is stack terms is called push. An element is retrieved also from the top of the list, in stack, this is called pop Other important function is first which returns the value of the element which is at the top; however it does not remove it from the list. Similar to Stack, a Queue also stores list of elements, an element is inserted at the end of the queue, this function is called enqueue, the element is removed from the top of the list, this in queuing terms is called dequeue. Similar to stack, it also has function first with similar functionality. You role is to provide implementation for these data structures, with all the functionality mentioned above.Explanation / Answer
#include<iostream.h>
struct node {
int data;
struct node *next;
};
class Stack {
private:
node *top;
public:
Stack(){
top = NULL;
}
void push(int a){
node *temp = new(struct node);
temp->data = a;
temp->next = NULL;
if (top == NULL){
top = temp;
}
else {
temp->next = top;
top = temp;
}
}
int public pop(){
if (top == NULL){
cout << "Stack is empty";
return -1; //Assuming -1 means Stack is empty
}
else {
return top->data;
top = top->next;
}
}
int first(){
if (top == NULL){
cout << "Stack is empty";
return -1;
}
else {
return top->data;
}
}
};
class Queue {
private:
node *head;
public:
Queue(){
head = NULL;
}
void enqueue(int n){
node *p;
node *temp = new (struct node);
temp->data = n;
temp->next = NULL;
if (head == NULL){
head = temp;
}
else {
p = head;
while (p->next != NULL)
p = p->next;
p-next = temp;
}
}
int dequeue pop(){
if (top == NULL){
cout << "Queue is empty";
return -1; //Assuming -1 means Queue is empty
}
else {
return head->data;
head = head->next;
}
}
int first(){
node *p;
if (head == NULL){
cout << "Queue is empty";
return -1;
}
else {
return head->data;
}
}
};