【问题标题】:Way to access stack top element to recursively compare if both stack elements are the same访问堆栈顶部元素以递归比较两个堆栈元素是否相同的方法
【发布时间】:2020-06-04 09:09:29
【问题描述】:

如何访问每个堆栈的顶部元素以便比较它们?我使用 (iTop,i2Top,nTop,n2Top) 因为我一直在测试以使其工作,但我似乎无法获得正确的输出。 我做错了什么?

我认为这会起作用,但事实并非如此。基本上我想引用堆栈的顶部元素,并将其与stack2的顶部元素进行比较。然后,如果它们相等,则弹出它们并对堆栈的其余部分执行相同的操作。最后,如果堆栈是空的,因为所有元素都相同并被弹出,那么堆栈确实是相同的。并推回堆栈 1 和堆栈 2。 谢谢

public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; // 
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }   
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}
public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty


        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; // 
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }   
            return t;
        }       


        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else      
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class

【问题讨论】:

  • peek pop 接受。
  • 而不是弹出所有内容进行比较,而是创建一个返回 StackArray 数组的私有方法。您可以直接比较两个数组。
  • 抱歉,我没有注意到您希望使用递归。 sameStack 的顶级版本看起来您的想法是正确的。
  • 这似乎是一种非常不寻常的检查相等性的方法。您是否有理由希望使用递归和弹出/推送?
  • @sprinter 是的,这是明天到期的家庭作业,这就是我浪费了 Wholeeeeeee 一天的要求

标签: java arrays data-structures stack compare


【解决方案1】:

只需迭代items 数组并使用equals()(不是==)比较元素。

public boolean sameStack(StackArray<E> s2) {
    if (this.top != s2.top) {
        return false;
    }
    for (int i = 0; i <= this.top; i++) {
        if (! this.items[i].equals(s2.items[i])) {
            return false;
        }
    }
    return true;
}

这是可行的,因为StackArray 的任何方法都可以访问StackArrayprivate 成员,无论是当前实例(this)还是其他实例(例如s2)。

【讨论】:

  • 您还应该检查两个堆栈的元素数量不同的情况。
  • @NomadMaker 你认为这句话有什么作用? if (this.top != s2.top)
  • @Andreas 唯一的问题是我不允许使用 .equals 来满足我的作业要求
【解决方案2】:

如果您特别需要使用递归来测试堆栈的相等性,那么更简单的方法是将索引传递给方法。那么你就不需要push和pop了。

public boolean equals(Stack<E> other) {
    return equalsFrom(other, 0);
}

private boolean equalsFrom(Stack<E> other, int from) {
    if (from >= this.top || from >= other.top)
        return from >= this.top && from >= other.top;
    else
        return this.items[from].equals(other.items[from])
            && equalsFrom(other, from + 1);
}

希望这种方法对您有意义。 if 语句的第一个分支可以读作“如果我已经到达任一堆栈的末尾,那么我必须已到达两个堆栈的末尾才能使它们相等”。第二个分支可以读作“如果我没有到达任一堆栈的末尾,则当前元素必须相等,其余堆栈必须相等,整个堆栈才能相等”。

【讨论】:

  • 我只能使用push pop和peek
【解决方案3】:

许多小时后海绵宝宝模因............终于自己想出来了!

import java.util.NoSuchElementException;

public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
               System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }

        public E pop() {
             if (isEmpty()==true) {
                   System.out.println("Stack Empty!");
                }
             else{
            E e = (E) items[top];
            items[top] = null;
            top = top-1;
            return e;
             }
            return null;
        }

        public boolean isFull() {
             if (top == items.length-1) {
                 return true;
             }
             return false;
        }

        public boolean isEmpty(){
             if (top==-1) {
                 return true;
             }
             return false;
        }

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
             for(int i = 0; i < items.length ;i++) {
                 System.out.print(items[i]+" ");
        }
             System.out.print("}");
            return "";
    }

        public int peek() {
            if (this.isEmpty()) throw new NoSuchElementException("Stack underflow");
            //System.out.println("items[top]"+this.items[top]);
            //System.out.println("e"+e);
            return (int) this.items[top];
        }


        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }

            if ((int) this.peek() == s2.peek()) {
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                this.push(t1);
                s2.push(t2);
            }
            else {
                t = false;
                return t;
            }   
            return t;           
        }

        public static void main(String[] args) 
        {
            // Code reference for sameStack method
           StackArray<Integer> stack = new StackArray<Integer>();
           StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(122);
            stack.push(222);
            stack.push(3313);
            stack.push(46);
            stack2.push(122);
            stack2.push(222);
            stack2.push(3313);
            stack2.push(46);
            System.out.println(stack);
            System.out.println(stack2);

            stack.peek();
            if (stack.sameStack(stack2) == true) {
                System.out.println("They are equal");
            }
            else {
                System.out.println("They are NOT equal");
            }

            System.out.println(stack);
            System.out.println(stack2);

            //Calling comparison method
           // stack.sameStack(stack2); 
        }
}

【讨论】:

    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 2021-08-06
    • 2010-10-28
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多