【问题标题】:Adding elements to the front of a queue without using STL不使用 STL 将元素添加到队列的前面
【发布时间】:2018-05-01 03:07:37
【问题描述】:

我正在尝试将一些元素添加到已经有其他项目的队列的前面。我的代码工作正常,但它每次都会在前面添加项目。如何修改它以在前面添加一个之后添加下一个项目。这是我得到的:

void Queue::addtoFront(string first, string last){
 Node *temp = new Node(first, last, NULL);
    temp->next = head;
        head = temp;
}

【问题讨论】:

  • 您希望它始终在队列的后面(靠近 NULL 指针)或第二个元素(前面后面的那个)添加一个元素?
  • 听起来你想要一个addQueueToFront 函数。使用您想要的顺序构建第二个队列,然后一次添加整个队列。
  • 在前面添加项目后,我使用此功能添加的下一个项目应该在另一个前面的之后
  • 这将违反 addtoFront 这样的名称所暗示的合同。如果你真的希望这种行为,我推荐一个不同的名字。
  • 这些是我想添加到前面的一些特殊项目,但它应该是先进先出,我怎么可能改变它?这些项目会放在前面,但在第一个前面添加一个之后,第二个应该在之后

标签: c++ algorithm data-structures linked-list queue


【解决方案1】:

注意:我不确定您要达到什么目的,但您可以编写一个“insertAfter”成员函数。该函数接受一个新元素并将其插入到链表中给定元素之后。

为此,您必须首先设置新元素的“下一个”链接,然后在请求的元素之后立即插入新元素。

void Queue::insert(Node *newElement, Node *insertAfter)
{
    _ASSERT(insertAfter != nullptr);
    _ASSERT(newElement != nullptr);
    // set the 'next' of the new element to the 'next' of the insertAfter
    newElement->next = insertAfter->next;
    // now insert the new element immediately after the 'insertAfter'
    insertAfter->next = newElement;
}

// Taken from the original post...
// Of course, "addToFront" is no longer the correct name for this function,
// since it does no longer add the element to the front
void Queue::addToFront(...)
{
    if (head==nullptr) {
        // see original post above
    } else {
        // insert new element at the 2nd position in the queue,
        // immediately behind the head
        insert(temp, head);
    }
}

为了进一步研究,您可以阅读链表并查看 std::list 接口。您可能希望使用 shared_ptr/unique_ptr 来改进您的代码,而不是使用 Node*。在现代 C++ 中,您几乎不会使用

Node *element=new Node();

大多数时候这只是糟糕的代码。自己管理指针和对象生命周期是一种 引发各种令人讨厌的问题(内存泄漏、访问冲突、 浅拷贝与深拷贝问题,尤其是无法释放对象。在例外等之后......)。使用托管或智能指针让您的生活更轻松:

shared_ptr<Node> element(new Node());
// or even better
shared_ptr<Node> element=std::make_shared<Node>();

注意:“托管/智能指针”与 C#/C++ 托管代码无关。这个名字只是说有一个类 (shared_ptr) 可以进行某种自动管理并承担您的一些负担。

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2018-10-01
    • 2011-12-18
    相关资源
    最近更新 更多