在链表堆栈中实现赋值运算符

时间:2017-10-23 23:54:22

标签: c++ linked-list stack deep-copy

我正在尝试为链表堆栈执行深层复制赋值运算符。我想我已经把头脑包裹在我需要做的事情上,但我无法理解它。

这是我的代码:

// Purpose: performs a deep copy of the data from rhs into this linked stack
// Parameters: rhs is linked stack to be copied
// Returns: *this
// Postconditions: this stack contains same data values (in the same order) as are in rhs; any memory previously used by this stack has been deallocated.
template <typename T>
const LinkedStack<T>& LinkedStack<T>::operator=(const LinkedStack<T>& rhs) {
    while(rhs.m_head != NULL) {
        m_head->m_data = rhs.m_head->m_data;
        m_head->m_next = new Node<T>();
        rhs.m_head = rhs.m_head->m_next;
        m_head = m_head->m_next;
    }
    m_size = rhs.m_size;
}

所以我的思考过程是复制数据,创建一个新节点,然后从rhs变量中弹出一个节点。

目前错误在&#34; rhs.m_head = rhs.m_head-&gt; m_next;&#34; for&#34;错误:分配成员&LinkedStack :: m_head&#39;在只读对象&#34;。我不知道如何解决这个问题,因为我传递了一个不变的参考。

我哪里错了?

节点标题(模板化):

template <class T>
class Node {
public:
  T m_data;            // Data to be stored
  Node<T>* m_next;     // Pointer to the next element in the list

  Node() : m_next(NULL) {}
  Node(const T& x, Node<T>* p) : m_data(x), m_next(p) {}
};

链接堆栈标题(模板化):

template <class T>
class LinkedStack {

  Node<T>* m_head;     // Pointer to the top of the stack
  int m_size;          // The number of elements in the stack

public:
  LinkedStack();
  ~LinkedStack();
  const LinkedStack<T>&  operator= (const LinkedStack<T>& rhs);    
  bool isEmpty() const;
  const T& top() const throw (Oops);
  void push(const T& x);  
  void pop();
  void clear();
};
编辑:找到解决方案。

template <typename T>
const LinkedStack<T>& LinkedStack<T>::operator=(const LinkedStack<T>& rhs) {
    clear();

    Node<T>* temp = rhs.m_head;

    m_head = new Node<T>();
    Node<T>* c_head = m_head;

    while(temp != NULL) {
        m_head->m_data = temp->m_data;
        temp = temp->m_next;
        m_head->m_next = new Node<T>;
        m_head = m_head->m_next;
    }

    m_head = c_head;
    m_size = rhs.m_size;

    return *this;
}

我的主要问题是在开始使用m_next之前忘记将m_head重置为原始头部。

0 个答案:

没有答案