【问题标题】:How would I write a pop_front function for a list?如何为列表编写 pop_front 函数?
【发布时间】:2014-05-10 04:22:32
【问题描述】:

作为练习,我正在创建自己的名为 List 的容器类模板。它是一个基于模板的单端链表,节点是一个嵌套在链表本身中的结构体,如下所示:

template<typename T>
class list
{
protected:
    struct node
    {
        T data;
        node* link;
    };
    node* head;
    //Rest of the code after here
};

容器有两个函数来构建列表:push_front 和 pop_front。我设法弄清楚了 push_front 函数,但是我无法弄清楚如何编写 pop_front 函数。 pop_front 函数删除列表的头部并将列表中的下一个值设置为头部。我不知道实际的 pop_front 函数是如何工作的,所以我被困在这里。接下来我该怎么做?

【问题讨论】:

  • 请说明您是在尝试编写pop_front 方法还是pop_back 方法。您在问题中使用了这两个名称。
  • 哦,对不起。这是一个pop_front。

标签: c++ class linked-list stl singly-linked-list


【解决方案1】:

我不知道你会怎么写这个函数。至于我,我会这样写。

void pop_front()
{
   if ( head )
   {
      node *tmp = head;
      head = head->link;
      delete tmp
   }
}

【讨论】:

  • 嗯,没有返回值?
  • 这就是 std::list 所做的。 cplusplus.com/reference/list/list/pop_front
  • 您能澄清一下next 的作用吗?它是容器中的下一个值吗?
  • @FiveOutOfFive 我相信和你的链接成员一样。
  • @FiveOutOfFive 这是一个错字。我在链接旁边更改了。
猜你喜欢
  • 2017-04-05
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 2018-04-21
  • 2015-07-24
  • 1970-01-01
相关资源
最近更新 更多