Use Double Linked list to write the solution. I know how to implement this using
ID: 3743205 • Letter: U
Question
Use Double Linked list to write the solution. I know how to implement this using a single linked list. Comment the code.
Write a C++ class (or a set of classes) that implements a stack using a double linked list. The type of data contained in the stack should be int. The maximum size of the stack is 50. Implement the following methods: . Constructor and destructor; I 5 points . void push (int value); // pushes an element with the value into the stack. 5 points int pop 0:/pops an element from the stack and returns its value. 10 points int isEmpty0:// returns 1 if the stack is empty, O otherwise. 5 points . int numOfElements0:// returns the number of elements in the stack. 5 points void printElements0;/ print out the current stack to the console. 5 points A main function; /execute each method of your stack (except the destructor) at least once without asking input from the users. 15 points.Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using std::cout;
class Node
{
public:
Node *prev;
Node *next;
int shares;
float pps;
Node(int vshares)
{
shares = vshares;
prev = next = nullptr;
}
};
class dlist
{
public:
Node *head;
Node *tail;
dlist()
{
head = tail = nullptr;
}
~dlist()
{
destroy();
}
void push_back(int shares)
{
Node *node = new Node(shares);
if (head == NULL)
{
head = tail = node;
}
else
{
tail->next = node;
node->prev = tail;
tail = node;
}
}
void destroy()
{
Node *walk = head;
while (walk)
{
Node *node = walk;
walk = walk->next;
delete node;
}
head = tail = nullptr;
}
};
class stack
{
public:
int maxsize;
int count;
dlist list;
stack()
{
count = 0;
maxsize = 50;
}
void push(int num)
{
if (count < maxsize)
{
list.push_back(num);
count++;
}
}
void pop()
{
Node *tail = list.tail;
if (!tail)
{
return;
}
if (tail == list.head)
{
delete tail;
list.head = list.tail = nullptr;
count--;
}
else
{
Node *temp = list.tail->prev;
delete list.tail;
list.tail = temp;
list.tail->next = nullptr;
count--;
}
}
void printElements()
{
Node *walk = list.head;
while (walk)
{
cout << "(" << walk->shares << "," << walk->pps << ") ";
walk = walk->next;
}
cout << " ";
}
void isempty()
{ Node *emp = list.head;
if(emp==NULL)return 1;
else return 0;
}
void numberOfElements()
{ Node *current = list.head;
int count = 0; // Initialize count
while (current != NULL)
{
count++;
current = current->next;
}
cout<<count;
}
};
int main()
{
stack s();
s.push(11);
s.push(12);
s.push(13);
s.push(14);
s.printElements();
s.isempty();
s.numberOfElements();
s.pop();
s.printElements();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.