【问题标题】:Queue implementation with Linked list in C++在 C++ 中使用链表实现队列
【发布时间】:2016-11-27 21:18:36
【问题描述】:

我正在尝试基于链表在 C++ 中实现队列容器。我使用相同的结构来实现 Stack 并且效果很好。

但现在我对“入队”方法没有任何问题。我不明白到底是什么问题,虽然我知道指针是我的弱点。

#include <iostream>

template <class N>
class node {
public:
  N data;
  node* next;
};

template <class Q>
class my_queue {
protected:
  node<Q>* m_head;
  unsigned int m_size;

public:
  my_queue() {
    m_head = NULL;
    m_size = 0;
  }

  void enqueue(Q value) {

    node<Q>* newel = new node<Q>; // creating the new element
    node<Q>* last = m_head; // find the last element in the queue

    while(last != NULL) {
      last = last->next;
    }

    newel->data = value;
    newel->next = last->next;
    last->next = newel;

    m_size++;
  }

  void print() {
    node<Q>* element = m_head; // element == each element in the list
    while(element != NULL) {
      std::cout << element->data << std::endl;
      element = element->next;
    }
  }

};

如果我编译这个:

main() {
  my_queue<int> q;
  q.enqueue(1);
  q.enqueue(2);
  q.enqueue(3);
  q.enqueue(4);
  q.enqueue(5);
  q.print();

  return 0;
}

我没有收到任何错误,但是当我运行它时,我收到“分段错误”。

【问题讨论】:

  • 当你插入第一个元素时,last 将是m_head,它从未被分配,所以你不能做last-&gt;next = newel
  • 感谢解决方案的一部分!

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


【解决方案1】:

函数中的这个循环之后

while(last != NULL) {
  last = last->next;
}

指针last 将始终等于NULL。因此,由于这些语句,该函数具有未定义的行为

newel->next = last->next;
last->next = newel;

函数可以改写如下方式

void enqueue( const Q &value ) 
{
    node<Q> *newel = new node<Q> { value, nullptr };

    if ( m_head == nullptr )
    {
        m_head = newel;
    }
    else
    {
        node<Q> *last = m_head; // find the last element in the queue

        while ( last->next != nullptr ) last = last->next;

        last->next = newel;
    }

    m_size++;
}

为了让队列更高效,最好基于一个双边列表来实现。

【讨论】:

  • 太好了,谢谢 :) 有趣的是,在您添加修改后的代码之前,我在阅读您的评论后以完全相同的方式重写了它:)
  • 双面列表是什么意思?
  • @0x499602D2 它是一个有尾指针的单链表。因此,可以将新节点添加到列表的任何一侧。
  • 我的例子是一个单链表(每个节点只有一个链接到另一个元素,即“下一个”)。双链表中的节点将有两个链接:“下一个”和“上一个”。见:en.wikipedia.org/wiki/Doubly_linked_list
  • @vgratian 您可以将尾节点再添加一个节点到您的队列中。在这种情况下,将新节点添加到队列尾部会更有效率。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多