我一直在研究关于java中堆栈的大学任务,但我似乎无法找到这项任务的帮助。它涉及到交换机路由,我需要使用堆栈进行此分配。作业明天到期,但没有必要急于回答,因为我只是在寻找解决方案,而不是等级。由于问题不是用英文写的,我会简短解释。
开关盒包含4n个引脚,盒子两侧各有n个引脚。只有当连接一对引脚的线路都不与另一条引线相交时,开关盒才可以路由。输入将是成对的连接引脚号。
我发现但可以理解的一些可能的解决方案: 这个问题可以通过与括号匹配的算法类似的算法来解决 2.将引脚号放在堆栈和数组中并进行比较(这是最令人困惑的)
到目前为止我的代码(尝试第二种算法):
import java.util.Scanner;
import java.util.Stack;
public class Tester {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int cases=sc.nextInt();
for(int i=0;i<cases;i++){
int pin=sc.nextInt();
SwitchBox box=new SwitchBox(pin);
for(int j=0;j<pin*4;j++){
box.add(sc.nextInt());
}
boolean res=box.isRoutable();
if(res){
System.out.println("routable");
}
else{
System.out.println("not routable");
}
}
}
static class SwitchBox{
Stack<Integer> pins;
int[] pairs;
int[] comparator;
public SwitchBox(int pin){
this.pins=new Stack<Integer>();
this.pairs=new int[(pin*4)];
this.comparator=new int[this.pairs.length];
}
public boolean isRoutable(){
Stack<Integer> s=new Stack<Integer>();
for(int i=0;i<pairs.length;i++){
pairs[i]=pins.peek();
s.push(pins.pop());
}
for(int i=pairs.length-1;i>=0;i--){
if(pairs[i]!=s.pop()){
return true;
}
}
return false;
}
public void add(int pinNum){
if(pins.isEmpty()){
pins.push(pinNum);
}
else{
Stack<Integer> temp=new Stack<Integer>();
int top=(int)pins.peek();
while(top>pinNum){
temp.push(pins.pop());
if(pins.isEmpty()) top=pinNum;
else top=(int)pins.peek();
}
pins.push(pinNum);
while(!temp.isEmpty()){
pins.push(temp.pop());
}
}
}
}
}
答案 0 :(得分:0)
在您的add
方法else
阻止错误。我无法理解你尝试做什么,但你需要做下一件事
public void add(int pinNum) {
if (pins.isEmpty()) {
pins.push(pinNum);
} else {
Integer last = pins.peek();
if (last == pinNum) {
pins.pop();
} else {
pins.push(pinNum);
}
}
}
在isRoutable
方法之后只需要检查pins
堆栈。如果它是空的,那么一切都很好。否则就会有相交的线条。