このヘッダーに基づいて (リンクされたリストを使用して) C++ キューを作成する必要があります。
class queue
{
public:
queue(); // constructor - constructs a new empty queue.
void enqueue( int item ); // enqueues item.
int dequeue(); // dequeues the front item.
int front(); // returns the front item without dequeuing it.
bool empty(); // true iff the queue contains no items.
int size(); // the current number of items in the queue.
int remove(int item); // removes all occurrances of item
// from the queue, returning the number removed.
private:
class node // node type for the linked list
{
public:
node(int new_data, node * prev_node, node * next_node){
data = new_data ;
next = next_node ;
prev = prev_node ;
}
int data ;
node * next ;
node * prev ;
};
node * front_p ;
node * back_p ;
int current_size ; // current number of elements in the queue.
};
これが私がこれまでに持っているものです:
#include <iostream>
#include "queue.h"
using namespace std;
queue::queue(){
current_size = 0;
front_p = new node(NULL, NULL, NULL);
back_p = new node(NULL, NULL, NULL);
}
void queue::enqueue(int item){
if (current_size == 0){
node * new_node;
new_node = new node(item, back_p, front_p);
front_p->prev = new_node;
back_p->next = new_node;
current_size = current_size + 1;
}
else if (current_size > 0){
node * new_node;
new_node = new node(item, back_p, back_p->next);
back_p->next = new_node;
new_node->next->prev = new_node;
current_size = current_size + 1;
}
}
int queue::dequeue(){
if (current_size > 0) {
node *remove = front_p->prev;
return remove->data;
remove-> prev->next = front_p;
front_p->prev = remove->prev;
delete remove;
current_size = current_size - 1;
}
else if (current_size == 0) {
return NULL;
}
else {
return NULL;
}
}
int queue::front(){
return front_p -> prev -> data;
}
bool queue::empty(){
return current_size == 0;
}
int queue::size(){
return current_size;
}
int queue::remove(int item){
for (int i = 0; i < current_size; i++){
}
return NULL;
}
int main(){
int int1, int2;
cout << "Welcome to the double linked list test program" << endl << "Please enter a #" << endl;
cin >> int1;
cout << "Another number" << endl;
cin >> int2;
queue * main_queue;
main_queue = new queue();
main_queue->enqueue(int1);
main_queue->enqueue(int2);
cout << "The front element is: " << main_queue->front() << endl;
cout << "I have dequeued: " << main_queue->dequeue() << endl;
cout << "The front element now: " << main_queue->front() << endl;
}
しかし、プログラムを実行すると、同じ数値が 3 回表示されます。これは、適切にデキューされていないことを示していますか?