0

在过去的几个小时里,我创建了一个方法,该方法将从堆栈 s1 中获取空元素,并将它们放入 s2 中。然后该类应打印堆栈。方法如下

import net.datastructures.ArrayStack;
import net.datastructures.Stack;
import javax.imageio.IIOException;

public class Stacks {
    public static <E> void compress(Stack<E> s1, Stack<E> s2) {
        int counter = 0;
        while (!s1.isEmpty()) {
            s1.peek();
            if (s1.peek() == null) {
                s1.pop();        
            } else if (s1.peek() == !null) {
                s1.pop();
                s2.push();
                counter++;
            }
            for (counter=10;counter>s1.size(); counter--){
            }
            s2.pop();
            s1.push();
        }    
    }

    public static void main(String[] args) {
        // test method compress
        Stack<Integer> S1 = new ArrayStack<Integer>(10);
        S1.push(2);
        S1.push(null);
        S1.push(null);
        S1.push(4);
        S1.push(6);
        S1.push(null);
        Stack<Integer> s2 = new ArrayStack<Integer>(10);
        s2.push(7);
        s2.push(9);
        System.out.println("stack S1: " + S1);
        // prints: "stack S: [2, null, null, 4, 6, null]"
        System.out.println("stack s2: " + s2);
        // prints: "stack X: [7, 9]"
        compress(S1, s2);
        System.out.println("stack S1: " + S1);
        // should print: "stack S: [2, 4, 6]"
        System.out.println("stack s2: " + s2);
        // should print: "stack X: [7, 9]"
    }
}

Eclipse 给我 peek() 和 push() 方法的错误;它允许 pop() 方法。我的理解是这些方法是继承的?任何帮助深表感谢!

4

3 回答 3

4
else if (s1.peek() == !null) 

这是不正确的。用这个:

else if (s1.peek() != null) 
于 2013-02-22T16:45:50.300 回答
1

这个:

    if (s1.peek() == null) {
        s1.pop();

    } else if (s1.top() == !null) {
        s1.pop();
        s2.push();

        counter++;
    }

应该:

    if (s1.top() == null) {
        s1.pop();

    } else {
        s2.push(s1.pop());

        counter++;
    }

您无需仔细检查s1.peek()is not null。另外,!null不是正确的语法。

我编辑了我的答案以使用top()而不是peek()pop() s1进入s2

于 2013-02-22T16:48:43.770 回答
1

除了比较错误之外,您还有一些语法错误:

push()需要一个参数:你在压栈什么?即使它是null它仍然需要是s1.push(null)。如果这是你正在做的事情pop(),你需要将结果分配pop()给某个东西——现在它正在消失在以太中。

您正在使用的对象(net.datastructures.Stack)没有peek()方法;相反,它具有top()执行相同功能。

于 2013-02-22T16:50:33.863 回答