【问题标题】:C++ Singly Linked List - Deque - InsertFront()C++ 单链表-双端队列-InsertFront()
【发布时间】:2017-02-28 14:37:06
【问题描述】:

我正在尝试为我的单列双端队列实现一个 insertfront() 函数,但我一直遇到同样的问题。

我相信这是由于运算符的重载=

Deque& operator=(const Deque&){return *this;};

为了使分配工作,它需要操作数 A 是 Deque 类型的引用,操作数 B 是 Deque 类型的另一个引用,但我不确定如何实现这一点,因为我尝试执行 head& = new_node& 和遇到更多错误。

Deque.cpp||In member function 'void Deque::insert_front(int)':|
Deque.cpp|21|error: use of deleted function 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Node; _Dp = std::default_delete<Node>]'|
/usr/include/c++/6/bits/unique_ptr.h|357|note: declared here|

这是我的功能

#include "Deque.h"
#include <iostream>
#include <memory>
#include <utility>
using std::cout;
using std::endl;
using std::move;

void Deque::insert_front(int a)
{
    std::unique_ptr<Node> new_node;

    new_node->val = move(a);

    new_node->next = move(head);
    head = move (new_node);
}

双端队列.h

#include "Node.h"
#include <memory>
class Deque{
    public:
        Deque() = default;
        Deque(const Deque&);
        ~Deque(); //must use constant space
        Deque& operator=(const Deque&){return *this;};
        void insert_front(int); 

    private:

    friend Node;

        //Sentinel
        std::unique_ptr<Node> head ;
        std::unique_ptr<Node> tail ;
};

节点.h

#ifndef NODE_H
#define NODE_H

#include <iostream>
#include <memory>

class Node {
 public:
 Node(const Node& n) : val{n.val}, next{}
  {
  }
 Node(int v, std::unique_ptr<Node> n) : val{v}, next{move(n)}
  {
  }
 Node(int v) : val{v}
  {
  }

 private:
  int val = 0;
  std::unique_ptr<Node> next = nullptr;

  friend class Deque;
  friend std::ostream& operator<<(std::ostream&, const Node&);
};

#endif

【问题讨论】:

  • 您还需要将new_node 移动到head
  • 啊,对了,忘记粘贴了。 - 我很确定这是我的问题?你能把它作为答案,所以我可以给你答案点吗? :P

标签: c++ pointers compiler-errors linked-list smart-pointers


【解决方案1】:

在函数 insertAtFront 中,基本上很容易在创建节点后检查列表是否为空,因此我们可以通过头节点检查它是否为空,然后节点为空,否则不是。如果 head 不为空,那么我们在新节点的 next 指针中分配第一个节点的地址。然后我们必须更新 head,所以我们将新创建的节点地址分配给 head。

#include<iostream>
using namespace std;

//Node structure
struct node{
    int data;
    node* next;
};

//This pointer will always point first node
node* head = NULL;

//Function to add node at the front of the linked list
void insert_at_front(){
    node* t = new node;
    cout << "Enter the data in the node :";
    cin >> t->data;
    t->next = NULL;

    if(head == NULL){
        head = t;
    }
    else{
        //After adding the new node to the existing linked list 
        //then we have to modify the head pointer  
        t->next = head;
        head = t;

    }
    numberOfNodes++;
}
}

【讨论】:

  • 欢迎来到 SO!我们感谢您的意见,但请编辑您的答案并解释一下原因和方式。
猜你喜欢
  • 2011-03-18
  • 2018-07-02
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 2014-10-12
  • 1970-01-01
  • 2017-05-06
相关资源
最近更新 更多