我在一个类中生成一个全局链表(每个结点是一个结构),然后在另外一个类中一次取出,但是为什么下面的代码有错?(在取的时候总是得到链表最后一个结点的值)?哪儿错了?
typedef struct tagTest
{
int aa;
int bb;
}TEST, far *LPTEST;
typedef CList<LPTEST, LPTEST>CTestList;
//赋值
CTestList TestList;
for(int i = 0; i < 5; i ++)
{
TEST t;
t.aa = i;
t.bb = i * i;
TestList.AddTail(&t);
}
//取出来
POSITION pos = TestList.GetHeadPosition();
int n = TestList.GetCount();
POSITION nowpos = pos;
for(int j = 0; j < n; j ++)
{
nowpos = pos;
LPTEST t = NULL;
t = TestList.GetNext(nowpos);
int x= t->aa;            //x总是4,为什么?
int y = t->bb;             //y总是16,为什么?
}

解决方案 »

  1.   

    我就是DEBUG的时候发现不对的.
      

  2.   

    for(int j = 0; j < n; j ++)
    {
    nowpos = pos;  // 你不觉得这个地方有点问题么 ? 
    LPTEST t = NULL;
    t = TestList.GetNext(nowpos);
    int x= t->aa; //x总是4,为什么?
    int y = t->bb; //y总是16,为什么?
    }
      

  3.   

    //遍历
    int n = TestList.GetCount();
    LPTEST t = NULL;
    for(int j = 0; j < n; j ++)
    {
    t = TestList.GetAt(j);
    int x= t->aa;  
    int y = t->bb;
    }
      

  4.   

    忘了参数是POSITION 了
    仔细看看,你对POSITION 的作用理解有误,POSITION 只需声明一次,用于记录并维护内部状态,不需要再次赋值的LPTEST t = NULL;
    POSITION pos = TestList.GetHeadPosition();
    do{
      t = TestList.GetNext(pos);
      int x= t->aa;
      int y = t->bb;
    }while(pos); 如果用原来的代码:
    POSITION pos = TestList.GetHeadPosition();
    int n = TestList.GetCount();
    //POSITION nowpos = pos;//去掉该行
    for(int j = 0; j < n; j ++)
    {
    //nowpos = pos;//去掉该行
    LPTEST t = NULL;
    t = TestList.GetNext(pos/*nowpos*/);//修改一下
    int x= t->aa;
    int y = t->bb;
    }
      

  5.   

    好象不是POS的问题,为什么只能得到链表的最后一个结点,前面的都得不到?难道是链表的每个结点都指向同一个结构了?哪位高手帮忙修改修改.
      

  6.   

    我的理解啊。你的链表的指针
    for(int i = 0; i < 5; i ++)
    {
    TEST t;
    t.aa = i;
    t.bb = i * i;
    TestList.AddTail(&t);
    }
    这里你添加了地址到链表里。但是for每结束一个循环。你的TEST就把上次的空间释放了。所以你的指针可能就无效了
    你用动态分配看看呢》
                      LPTEST t = new  TEST;
      

  7.   

    像上面的。动态分配啊。就是用NEW
              因为你每个循环没有DELETE吗。所以就还在啊。然后在你链表用完的时候在释放就好了啊。