我想写一个双向链表的下标访问的函数,具体意思如下:
L1[1]=5; 首先,L1是一个双向链表的对象,执行完这条语句后,L1中的第二个元素变成5,
大概就跟C语言里面数组的访问方式一样,不知道我解释清楚了没有。
我遇到的问题就是,具体的函数实现在下面,但是执行完这个逻辑后,L1[1]的next域就
指向NULL了,我对此很是迷惑。
Node& operator[](size_t index)
{
if (index <= _size)
{
Node* Head = _pHead;
while (index--)
{
Head = Head->_pNext;
}
Node* tmp = Head;
tmp->_pNext = Head->_pNext;
tmp->_pPre = tmp->_pPre;
return *tmp;
}
}
Node* tmp = Head;
tmp只是复制了一个指针,但是它指向的内容还是原来链表的,你去改变它的next pre当然原来的链表跟着动了,你得用tmp = malloc(sizeof(Node))来创建
Node& operator[](size_t index)
{
if (index <= _size)
{
Node* Head = _pHead;
while (index--)
{
Head = Head->_pNext;
}
Node* tmp = new Node;
tmp = Head;
//tmp->_pNext = Head->_pNext;
//tmp->_pPre = tmp->_pPre;
return *tmp;
}
}