您的位置:首页 > 理论基础 > 数据结构算法

数据结构基础(C++版)(张力译版)校正 之二 .

2012-11-20 11:29 615 查看
page 155--156

1. 很显然 155 页的倒数第二行的 if(!out[i]) 应改为:if(!out[j]);

2. 156 页的关于delete delnode; 因为在前面的出栈入栈操作时打乱了原来的链表所以通过此处循环释放内存不可取,

我想,咱们可以在出栈操作后释放内存。例如:

if(!top)break;

x=first[top->data];

ENode *t=top;

top=top->link;

delete t;


另外,不需入栈的节点也要释放:

if (!out[j])

{

cout<<","<<j;

out[j]=true;

ENode *y=x->link;

x->link=top;

top=x;

x=y;

}

else

{

ENode *t=x;

x=x->link;

delete t;

}


一下是我的代码供参考:

#include "ENode.h"

#include <iostream>

using namespace std;

void Equivalence()

{

cout<<"input the numbers of the pairs :"<<endl;

int n=0;

do

{

cin>>n;

if (n>0)break;

else

cout<<"input the numbers of the pairs(must bigger than 0):"<<endl;

} while (1);

ENode **first=new ENode*
;

bool *out=new bool
;

fill(out,out+n,false);

// fill(first,first+n,0);

memset(first,0,n*sizeof(ENode*));

cout<<"input the pairs :"<<endl;

int i;

int t1,t2;

while(cin>>t1>>t2)

{

first[t1]=new ENode(t2,first[t1]);

first[t2]=new ENode(t1,first[t2]);

}

//找等价类

for (i=0;i<n;i++)

{

if (!out[i])

{

cout<<endl<<"A new class :";

cout<<i;

out[i]=true;

ENode *x=first[i];

ENode *top=0;

while (1)

{

while (x)

{

int j=x->data;

if (!out[j])

{

cout<<","<<j;

out[j]=true;

ENode *y=x->link;

x->link=top;

top=x;

x=y;

}

else

{

ENode *t=x;

x=x->link;

delete t;

}

}

if(!top)break;

x=first[top->data];

ENode *t=top;

top=top->link;

delete t;

}

}

}

// for (i=0;i<n;i++)

// while (first[i])

// {

// ENode *delnode=first[i];

// first[i]=delnode->link;

// delete delnode;

// }

delete[] first;

delete [] out;

}


///示例:

input the numbers of the pairs :

5

input the pairs :

0 1

2 3

1 4

4 0

^Z




A new class :0,4,1

A new class :2,3

Press any key to continue

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: