如果我将队列实现为一系列节点(值,指向下一个节点的指针),那么横穿该队列并检查特定值并编辑队列以使包含该值的所有节点的最佳方法是删除。但是队列的顺序将保持不变。
好的,这是描述所有功能的标题
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 * next_node ){
data = new_data ;
next = next_node ;
}
int data ;
node * next ;
};
node* front_p ;
node* back_p ;
int current_size ; // current number of elements in the queue.
};
这是 queue.cpp
#include "queue.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
queue::queue()
{
front_p = NULL;
back_p = NULL;
current_size = 0;
}
void queue::enqueue(int item)
{
node* newnode = new node(item, NULL);
if (front_p == NULL) //queue is empty
front_p = newnode;
else
back_p->next = newnode;
back_p = newnode;
current_size ++;
}
int queue::dequeue()
{
//if there is only one node
int value = front_p->data;
if (front_p == back_p)
{
front_p = NULL;
back_p = NULL;
}
//if there are two or more
else
{
node* temp = front_p;
front_p = temp->next;
delete temp;
}
current_size --;
return value;
}
int queue::front()
{
if (front_p != NULL)
return front_p->data;
}
bool queue::empty()
{
if (front_p == NULL && back_p == NULL)
return true;
else
return false;
}
int queue::size()
{
return current_size;
}
int queue::remove(int item)
{
//?????
}