60 342
Assignments Done
98%
Successfully Done
In April 2018

Answer to Question #62790 in C++ for Drek Evans

Question #62790
how to write a class that implements doubly linked list. Then implement a stack and queue using the doubly linked list class
Expert's answer
#include <iostream>

using namespace std;

class List {
public:
List(int v) {
next = prev = NULL;
val = v;
}

void setNext(List *n) {
next = n;
}
void setPrev(List *p) {
prev = p;
}

int getVal() {
return val;
}
List *getNext() {
return next;
}
List *getPrev() {
return prev;
}

private:
int val;
List *next;
List *prev;
};

class Stack {
public:
Stack() {
head = NULL;
}

void add(int val) {
List *v = new List(val);

if (head == NULL) {
head = v;
return;
}

v->setPrev(head);
head->setNext(v);

head = v;
}
int pop() {
int res = head->getVal();

List *v = head->getPrev();
delete head;

head = v;

return res;
}
private:
List *head;
};

class Queue {
public:
Queue() {
head = tail = NULL;
}

void add(int val) {
List *v = new List(val);

if (head == NULL) {
head = tail = v;
return;
}

v->setNext(tail);
tail->setPrev(v);

tail = v;
}
int pop() {
int res = head->getVal();

List *v = head->getPrev();
delete head;

head = v;

return res;
}
private:
List *head, *tail;
};


int main() {
int n = 10;

Stack *s = new Stack();

for (int i = 0; i < n; i++) {
s->add(i);
}

for (int i = 0; i < n; i++) {
cout << s->pop() << ' ';
}

cout << endl;

Queue *q = new Queue();

for (int i = 0; i < n; i++) {
q->add(i);
}

for (int i = 0; i < n; i++) {
cout << q->pop() << ' ';
}

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions