下面的代码是要实现两个链表的的链接,other是待链接的链表,it是指向想链接的那个元素的迭代器,
void splice(const_iterator pos, list& other, const_iterator it)
{
if (other.size() != 0)
{
if (it == other.begin())other.head = other.head->_next;
//auto it2 = it;
//++it2;
link_list(pos, it.getMynode(), it.getMynode()->_next);
if (other.size() == 0)free(other.head, other.tail);
}
}
link_list定义如下:
void link_list(const_iterator pos, NodePtr&sub_list, NodePtr&sub_tail)
{
sub_tail->_pre->_next = pos.getMynode();
sub_list->_pre->_next = sub_tail;
auto tmp = pos.getMynode()->_pre;
tmp->_next = sub_list;
pos.getMynode()->_pre = sub_tail->_pre;
sub_tail->_pre = sub_list->_pre;
sub_list->_pre = tmp;
if (head == pos.getMynode())head = sub_list;
}
出现的问题是这样的,给link_list传递参数用这种形式:link_list(pos, it.getMynode(), it.getMynode()->_next);
,
得到的结果是错误的,但是用下面的方法就是正确的:
auto it2 = it;
++it2;
link_list(pos, it.getMynode(), it2.getMynode());
出现问题的地方在这里:sub_tail->_pre->_next = pos.getMynode();
就是赋值之后,sub_tail的值也变成pos.getMynode()的值了,这是为什么?
//list节点
template<class T>
struct __list_node
{
typedef __list_node<T>* _NodePtr;
_NodePtr _pre;
_NodePtr _next;
T data;
};
typedef __list_node<T>* _NodePtr;
_NodePtr _Ptr; //指向链表节点的指针
//获取节点函数
_NodePtr&getMynode()
{
return _Ptr;
}
调用是这样的:
list<int>ilist1{1,2,3,4,5,6};
list<int>ilist2{ 555,333,999,5555};
ilist1.splice(++ilist1.begin(), ilist2,ilist2.begin());
Visual inspection should be because the subject's _next returns a copy of the linked list node