软件构造实验2 Poetic Walks

这篇博客介绍了软件构造实验中关于图的抽象数据类型实现,特别是`set`方法的详细逻辑。当权重为正时,该方法会添加或更新边,并在必要时添加顶点;权重为0时,删除边;若权重为负,则返回错误信息。代码通过迭代遍历边集合,使用`equals`方法比较顶点标签,实现了边的增删改操作,并确保了图的正确性。
摘要由CSDN通过智能技术生成

软件构造实验2 Poetic Walks

题目的2.1的要求

我们需要实现一个抽象数据类型图,需要完成图的一系列方法。
整体的实验过程就不细说了,主要讲一个里面需要实现的方法。

set

/**
* Add, change, or remove a weighted directed edge in this graph.
* If weight is nonzero, add an edge or update the weight of that edge;
* vertices with the given labels are added to the graph if they do not
* already exist.
* If weight is zero, remove the edge if it exists (the graph is not
* otherwise modified).
*
* @param source label of the source vertex
* @param target label of the target vertex
* @param weight nonnegative weight of the edge
* @return the previous weight of the edge, or zero if there was no such
* edge,返回-1如果输入的权值是负数.
*/

规约是这样的,总之就是weight是0则删除边;
大于0则设置边或更新权重(如果点还没在点集里需要使点增加到点集)(返回之前的权重,如果之前没有就返回0);
小于零则报错。

@Override public int set(L source, L target, int weight) {
        //throw new RuntimeException("not implemented");
    	if(weight<0) {
    		System.out.println("权值不能是负数");
    		checkRep();
    		return -1;
    	}
    	else if (weight > 0) {//添加或更新
    		Iterator<Edge<L>> iterator1 =edges.iterator();
    		while(iterator1.hasNext()) {
    			Edge<L> tmp=iterator1.next();
    			if(tmp.getsource().equals(source)  &&  tmp.gettarget().equals(target)) {
    				int pre=tmp.getweight();
    				iterator1.remove();
    				Edge<L> newone = new Edge<L>(source,target,weight);
    				edges.add(newone);
    				checkRep();
    				return pre;
    			}
    		}
    		vertices.add(target);
    		vertices.add(source);
    		Edge<L> newone = new Edge<L>(source,target,weight);
			edges.add(newone);
			checkRep();
			return 0;
    	}
    	else {//weight为0
    		int pre = 0;
    		Iterator<Edge<L>> iterator1 =edges.iterator();
    		while(iterator1.hasNext()) {
    			Edge<L> tmp=iterator1.next();
    			if(tmp.getsource().equals(source)  &&  tmp.gettarget().equals(target)) {
    				pre=tmp.getweight();
    				iterator1.remove();
    				break;
    			}
    		}
    		checkRep();
			return pre;
    	}
    }

我的代码也是基于这三种情况进行考虑的。
注意就是用equals去进行等值比较。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值