Reputation: 59
I have written the program below and overall it seems to work fine... Except that the remove() function keeps deleting all of the values in the queue without even being called...
#include <iostream>
#include <string>
using namespace std;
//Create a node struct
struct Node {
int data;
Node *next;
Node *prev;
};
class Queue {
private:
Node *head;
Node *tail;
int size;
public:
Queue();
~Queue();
void add(int d);
int remove();
bool isEmpty();
void printQueue(bool o);
};
//set to NULL
Queue::Queue() {
head = tail = NULL;
size = 0;
}
//destructor
//call remove until empty
Queue::~Queue() {
while (!isEmpty())
remove();
}
//adds a node with the given data at the back of the queue
void Queue::add(int d) {
Node *temp = new Node;
temp->data = d;
temp->next = NULL;
temp->prev = tail;
if (isEmpty()) {
//add to head
head = temp;
tail = temp;
cout << "Added: " << tail->data << endl;
} else {
//append
tail->next = temp;
tail = temp;
cout << "Added: " << tail->data << endl;
}
size++;
}
//removes the node at the head of the queue and returns its data
int Queue::remove() {
//TODO DOESNT WORK PROPERLY
if (isEmpty()) {
tail = NULL;
cout << "The queue is empty." << endl;
return 0;
} else {
Node *temp = head;
int value = head->data;
cout << "Removed: " << head->data << endl;
//moves pointer to next node
head = head->next;
if (head)
head->prev = NULL;
size--;
delete temp;
return value;
}
}
//determines if the queue is empty
bool Queue::isEmpty() {
return (size == 0);
}
//prints the contents of the queue from front to back, or front
//to back, depending on the value of the parameter
void Queue::printQueue(bool o) {
if (isEmpty()) {
cout << "The queue is empty." << endl;
} else {
Node *p;
if (o == true) {
p = head;
cout << "Printing front to back:" << endl;
//print front to back
while(p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
} else if (o == false) {
p = tail;
cout << "Printing back to front:" << endl;
//print back to front
while (p != NULL) {
cout << p->data << " ";
p = p->prev;
}
cout << endl;
}
}
}
int main() {
Queue q;
q.add(9);
q.add(10);
q.add(11);
q.add(12);
q.add(13);
q.add(14);
q.add(15);
q.add(16);
q.printQueue(true);
q.printQueue(false);
return 0;
}
In the main, remove() isn't even used, but the output is
Added: 9
Added: 10
Added: 11
Added: 12
Added: 13
Added: 14
Added: 15
Added: 16
Printing front to back:
9 10 11 12 13 14 15 16
Printing back to front:
16 15 14 13 12 11 10 9
Removed: 9
Removed: 10
Removed: 11
Removed: 12
Removed: 13
Removed: 14
Removed: 15
Removed: 16
Why does this keep happening? What can I do to fix it? Help, please :(
Thanks in advance!
Upvotes: 0
Views: 776
Reputation: 4951
The problem is probably not in the code actually, at a glance it behaves normally.
You declare Queue q;
as a local variable in your main. This means that when the main finishes it's execution, q goes out of scope, and the destructor is called.
Hope this sheds some light on the matter....
Upvotes: 1