我正在使用带有前哨节点的双向链接列表,该双向链接列表使双向链接列表成为循环列表(没有头,并且没有指向前后的指针,而是通过m_sentinel-> m_next引用head并引用tail到m_sentinel-> m_prev)。这是下面的代码:
在MyList.h中:
template <typename T>
class Node
{
public:
T m_element;
Node<T> *m_prev;
Node<T> *m_next;
// Helps make a dummy/sentinel/junk node
Node(Node<T> *in_prev, Node<T> *in_next):
m_prev(in_prev), m_next(in_next){}
Node(const T &x, Node<T> *in_prev, Node<T> *in_next):
m_element(x), m_prev(in_prev), m_next(in_next){}
};
template <typename T>
class MyList
{
private:
Node<T> *m_sentinel = nullptr;
int m_size;
public:
MyList();
~MyList();
MyList<T> & operator=(const MyList<T> &source);
void clear();
void push_back(const T &x);
在MyList.hpp中:
template <typename T>
MyList<T>::MyList()
{
m_size = 0;
m_sentinel = new Node<T>(NULL, NULL);
}
template <typename T>
MyList<T>::~MyList()
{
clear();
m_size = 0;
}
template <typename T>
MyList<T> & MyList<T>::operator=(const MyList<T> &source)
{
if(this == &source)
{
return *this;
}
while(source.m_sentinel->m_next != source.m_sentinel)
{
Node<T> *temp = source.m_sentinel->m_next;
push_back(temp->m_element);
source.m_sentinel->m_next = temp->m_next;
}
return *this;
}
template <typename T>
void MyList<T>::clear()
{
if(m_sentinel->m_prev == NULL && m_sentinel->m_next == NULL)
{
delete m_sentinel;
}
else
{
int k = size();
for(int i = 0; i < k; i++)
{
pop_back();
}
delete m_sentinel;
}
}
template <typename T>
void MyList<T>::push_back(const T &x)
{
Node<T> *newNode;
newNode = new Node<T>(x, NULL, NULL);
if(m_sentinel->m_prev == NULL && m_sentinel->m_next == NULL)
{
newNode->m_prev = m_sentinel;
newNode->m_next = m_sentinel;
m_sentinel->m_prev = newNode;
m_sentinel->m_next = newNode;
}
else
{
newNode->m_next = m_sentinel;
newNode->m_prev = m_sentinel->m_prev;
Node<T> *temp = newNode->m_prev;
m_sentinel->m_prev = newNode;
temp->m_next = m_sentinel->m_prev;
}
m_size++;
}
在main.cpp中:
#include "MyList.h"
int main()
{
MyList<int> x;
x.push_front(1);
x.push_front(2);
x.push_front(3);
x.push_front(4);
x.push_front(5);
x.push_front(6);
x.push_front(7);
MyList<int> p;
p = x;
// Below just outputs each linked list
int j = 0;
int m = x.size();
cout << endl << endl;
for(auto i = 0; i < m; i++)
{
cout << x.front() << endl;
x.pop_front();
j++;
}
cout << endl << endl;
j = 0;
m = p.size();
for(auto i = 0; i < m; i++)
{
cout << p.front() << endl;
p.pop_front();
j++;
}
cout << endl << endl;
运行此代码时,x确实会成功复制到p。当输出p时,给出以下输出:7 6 5 4 3 2 1,但是当输出x时,给出以下输出:-19823746 ...这只是垃圾内存值(告诉我x明显被改变了,但p成功获取了x的内容)。我不知道为什么它会改变。我正在寻找赋值运算符的修复程序/解决方案,因为它无法正常工作。
最佳答案
在MyList::operator=
内部,应该使用新变量而不是source.m_sentinel
成员本身进行迭代。这将更改实际列表,并且实际上正在删除节点。
使用此代替:
Node<T>* current = source.m_sentinel;
while (current->m_next != source.m_sentinel) {
Node<T>* temp = current->m_next;
push_back(temp->m_element);
current = temp;
}