gpt4 book ai didi

java - 检查两个堆栈是否相等的方法

转载 作者:行者123 更新时间:2023-12-01 18:48:03 25 4
gpt4 key购买 nike

给定 ArrayStack 的以下类定义:

Public class ArrayStack<T> implements Stack {

T[] stack;
int topIndex = -1;

在 ArrayStack 类中编写一个 equals(Stack other) 方法,该方法采用 Stack 作为参数,如果两个堆栈相等则返回 true,否则返回 false。

    public boolean equals(Stack<T> other) {

ArrayStack.java 代码

    import java.util.Arrays;
import java.util.EmptyStackException;

public class ArrayStack<T> implements Stacks<T> {

T[] stack;
int topIndex = -1;
private final static int DEFCAP = 100;

public ArrayStack(int maxSize) {
stack = (T[]) new Object[maxSize];
}

public ArrayStack() {
this(DEFCAP);
}

@Override
public void push(T element) {
if (topIndex == stack.length - 1) {
enlarge();
}
topIndex++;
stack[topIndex] = element;
}

@Override
public T pop() {
return stack[topIndex--];
}

@Override
public boolean isEmpty() {
return topIndex == -1;
}

@Override
public T peak() {
if (!isEmpty()) {
return stack[topIndex];
} else {
throw new EmptyStackException();
}
}

private void enlarge() {
stack = Arrays.copyOf(stack, stack.length + DEFCAP);
}
}

我的尝试:我对我的尝试有多糟糕感到非常生气,但我现在太封闭了,无法正确思考。请帮助思考这个问题!

public boolean equals(Stack<T> other) {
if(! other.isEmpty() ) {
for(int i=0; i < stack.length; i++) {
if(stack[i].equals(Other.stack[i]) ) {
return true;
}
}
}

return false;
}

谢谢!

最佳答案

public boolean equals(Stack<T> other) {
//If they point to the same object return true
if (stack == other) return true;
//Check for nulls
if (stack == null || other == null) return false;
//If the stacks are not the same length, then they won't be equal, easy first test case
if (stack.length != other.size()) return false;

for(int i=0; i < stack.length; i++) {
//Step through each item in both stacks, if any don't match return false
if(!stack[i].equals(other.stack[i]) ) {
return false;
}
}

//Haven't returned yet, they must be equal
return true;
}

关于java - 检查两个堆栈是否相等的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com