zoukankan      html  css  js  c++  java
  • 典型问题分析3—LinkList中遍历操作与删除操作混合使用

    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;
        }

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

  • 相关阅读:
    android 加入关屏
    网址导航收集
    OpenStack 中文社区
    Truncate 删除数据
    c# 实体类生成工具
    .net 关系
    html中,播放 flash
    Axis2.0+WebService的使用
    xfire java web服务器引擎
    修复 google paly
  • 原文地址:https://www.cnblogs.com/-glb/p/12345447.html
Copyright © 2011-2022 走看看