c++ - 从队列中删除所有项目c++

标签 c++ linked-list queue nodes

如果我有一个由一系列节点(值、指向下一个节点的指针)实现的队列,那么遍历该队列并检查特定值并编辑队列以使包含该值的所有节点的最佳方法是什么值将被删除。但队列的顺序将保持不变。

好的,这是描述所有功能的标题

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)
{
//?????
}

最佳答案

您需要遍历列表,检查每个节点的值。如果您看到序列 A -> B -> C,其中 B 是您要删除的值,则需要将链接从 A 更改为指向 C 而不是 B。

为了实现这一点,您需要保留对您看到的最后一个节点以及当前节点的引用。如果当前节点的值等于要删除的值,则将最后一个节点的下一个指针更改为当前节点的下一个指针。确保在继续之前释放当前节点的内存。

关于c++ - 从队列中删除所有项目c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13081702/

相关文章:

c - 如何减少 C 代码中的代码重复(由于空指针而不确定)

c - linux/list.h 中 container_of 宏背后的基本原理

Java - 获取方法上的锁获取

c++ - 为什么当线路已经平衡时 asm 期望 ()

c++ - linux, inotify - 如何订阅?

c++ - 为什么 dev C 不运行这个脚本?出于某种原因,它不喜欢我的 vector 声明

c++ - 如果我向 QTreeWidget 添加一个项目,它总是被插入到第一行

c++ - 为链表中的节点分配内存,没想到链表中的下一个节点也被分配了

grails - 如何在Grails应用程序中创建作业和队列

c# - 当我添加新项目时,列表会自动删除最旧的项目