本文主要是介绍数据结构基础(C++版)(张力译版)校正 之二 .,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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* [n];
bool *out=new bool[n];
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
这篇关于数据结构基础(C++版)(张力译版)校正 之二 .的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!