链表中指针的问题
请看下面的程序:
#include<iostream.h>
class CAT
{
public:
CAT (){itsAge=1;}
CAT(int age):itsAge(age){}
~CAT(){};
int GetAge()const{return itsAge;}
private:
int itsAge;
};
#if !defined(AFX_NODE_H__67D9A589_1C2B_449F_B9FB_FEF64A828786__INCLUDED_)
#define AFX_NODE_H__67D9A589_1C2B_449F_B9FB_FEF64A828786__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class Node
{
public:
Node();
Node(CAT*);
virtual ~Node();
void SetNext (Node*node){itsNext=node;}
Node*GetNext()const{return itsNext;}
CAT*GetCat()const{return itsCat;}
void Insert(Node*);
void Display();
private:
CAT*itsCat;
Node*itsNext;
};
#include "Node.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Node::Node(CAT*pCat):
itsCat(pCat),
itsNext(0)
{
}
Node::~Node()
{
cout<<"deleting node...\n;";
delete itsCat;
itsCat=0;
delete itsNext;
itsNext=0;
}
void Node::Insert(Node *newNode)
{
if (!itsNext)
itsNext=newNode;
else
{
int NextCatAge=itsNext->GetCat()->GetAge();
int NewAge=newNode->GetCat()->GetAge();
int ThisNodeAge=itsCat->GetAge();
if (NewAge>ThisNodeAge&&NewAge<NextCatAge)
{
newNode->SetNext(itsNext);
itsNext=newNode;
}
else
itsNext->Insert(newNode);
}
}
void Node::Display()
{
if (itsCat->GetAge()>0)
cout<<"Mycat is"<<itsCat->GetAge()<<"years old\n";
if (itsNext)
itsNext->Display();
}
#endif // !defined(AFX_NODE_H__67D9A589_1C2B_449F_B9FB_FEF64A828786__INCLUDED_)
void main()
{
Node*pNode=0;
CAT *pCat=new CAT(0);
int age;
Node *pHead=new Node(pCat);
while(1)
{
cout<<"new cat's age?(0 to quit):";
cin>>age;
if(!age)
break;
pCat=new CAT (age);
pNode=new Node(pCat);
pHead->Insert(pNode);
}
pHead->Display();
delete pHead;
cout<<"Existing...\n\n";
}
教科书上说if (NewAge>ThisNodeAge&&NewAge<NextCatAge)为真的话,通过
newNode->SetNext(itsNext);
itsNext=newNode;
上面两句就能实现新Node指向当前Node所指向的同一位置,当前Node指向新Node.
我不明白itsNext已经有了地址,再用newNode->SetNext(itsNext);会发生什么,
再用itsNext=newNode;又会发生什么,请高手指点,这个程序我已经看了三天了,还是不明白它是如何运行的。