码迷,mamicode.com
首页 > 其他好文 > 详细

典型问题分析3—LinkList中遍历操作与删除操作混合使用

时间:2020-02-22 15:33:13      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:int   find   http   code   返回   图片   --   soft   ios   

LinkList中遍历操作与删除操作混合使用

删除成功后,list.current()返回什么值?

#include <iostream>
#include "LinkList.h"

using namespace std;
using namespace DTLib;


int main()
{
    LinkList<int> list;

    for(int i=0; i<5; i++)
    {
        list.insert(i);
    }


    for(list.move(0); !list.end(); list.next())
    {
        if(list.current() == 3)
        {
            list.remove(list.find(list.current()));
            cout << list.current() <<endl;
        }
    }
  
    return 0;

}

打印结果:

技术图片

 

 

 这显然是一个随机值,那为什么会出现这种情况呢?

技术图片

 

 

 3所对应的堆内存已经被释放了,但是p指针却没有变化,还是指向原来内存。所以才会打印那个奇怪的值。

修改remove函数如下:

bool remove(int i)
    {
        bool ret = ((0<=i) && (i<m_length));

        if(ret)
        {
           Node* current = position(i);
           Node* toDel = current->next;

           if(m_current == toDel)
           {
                m_current = toDel->next;
           }
           current->next = toDel->next;

           m_length--;

           destroy(toDel);

          //  m_length--;
        }

        return ret;
    }

本篇文章想要说明,当删除链表中的一个元素时,不要忘记当前的指针也要移动哦。否则就会造成上面出现的现象。

典型问题分析3—LinkList中遍历操作与删除操作混合使用

标签:int   find   http   code   返回   图片   --   soft   ios   

原文地址:https://www.cnblogs.com/-glb/p/12345447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!