美文网首页常用算法
2019-08-04-使用俩个队列/栈实现一个栈/队列

2019-08-04-使用俩个队列/栈实现一个栈/队列

作者: 王元 | 来源:发表于2019-08-06 12:26 被阅读0次

1,问题:使用俩个队列实现一个栈

代码实现

private static class QueueToStack {

    public static final Queue<String> stack1 = new LinkedList<>();
    public static final Queue<String> stack2 = new LinkedList<>();

    public QueueToStack(String[] arr) {
        final int len = arr == null ? 0 : arr.length;
        for (int i = 0; i < len; i++) {
            stack1.offer(arr[i]);
        }
    }

    public void appendTail(String str) {
        stack1.offer(str);

    }

    public String deleteHead() {
        if(stack1.isEmpty()) {
            final int len1 = stack2 == null ? 0 : stack2.size();
            for (int i = 0; i < len1 - 1; i++) {
                stack1.offer(stack2.poll());
            }
            return stack2.poll();
        }
        if(stack2.isEmpty()) {
            final int len1 = stack1 == null ? 0 : stack1.size();
            for (int i = 0; i < len1 - 1; i++) {
                stack2.offer(stack1.poll());
            }
            return stack1.poll();
        }
        return null;
    }


    public int size() {
        return stack1.size() + stack2.size();
    }
}

调用方式

public static void main(String[] args) {
    String[] arr = {"a", "b", "c", "d"};
    QueueToStack queue = new QueueToStack(arr);
    queue.appendTail("f");
    System.out.println(queue.deleteHead());
    final int size = queue.size();
    for (int i = 0; i < size; i++) {
        System.out.println(queue.deleteHead());
    }

}

2,使用俩个栈实现一个队列

代码实现

private static class StackToQueue {

    public static final Stack<String> stack1 = new Stack<>();
    public static final Stack<String> stack2 = new Stack<>();

    public StackToQueue(String[] arr) {
        final int len = arr == null ? 0 : arr.length;
        for (int i = 0; i < len; i++) {
            stack1.push(arr[i]);
        }
    }

    public void appendTail(String str) {
        stack1.push(str);

    }

    public String deleteHead() {
        if(stack2.isEmpty()) {
            final int len = stack1.size();
            for (int i = 0; i < len; i++) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }


    public int size() {
        return stack1.size() + stack2.size();
    }
}

调用方式

public static void main(String[] args) {
    String[] arr = {"a", "b", "c", "d"};
    StackToQueue queue = new StackToQueue(arr);
    queue.appendTail("f");
    System.out.println(queue.deleteHead());
    final int size = queue.size();
    for (int i = 0; i < size; i++) {
        System.out.println(queue.deleteHead());
    }
}

相关文章

网友评论

    本文标题:2019-08-04-使用俩个队列/栈实现一个栈/队列

    本文链接:https://www.haomeiwen.com/subject/tpmudctx.html