我正在使用一个sentinel节点创建一个双链表,该节点使双链表成为一个循环列表(没有指向前面和后面的头指针和尾指针,相反,头由m_sentinel->m_next引用,尾由m_sensentinel->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;
}