数据结构基础(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值