用两个栈来实现队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014110320/article/details/77677242

If you push elements onto a stack and then pop them all, they appear in reverse order. If you repeat this process, they’re now back in order.
两个栈A和B,进栈的时候元素扔进去B中,出栈的时候出A中的元素,如果A中的元素为空,则将B中的元素以出栈的顺序放进A中。

下边代码部分仅供参考,因为没有经过严格的测试。

package coursera.week2.stackqueue;

import java.util.Iterator;

import org.omg.CORBA.Current;


public class Stack<Item> implements Iterable<Item>{

private Node first;

    private class Node {
        Item item;
        Node next;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public void push(Item item) {
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
    }

    public Item pop(){
        Item item = first.item;
        first = first.next;
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    public class ListIterator implements Iterator<Item>{

        private Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }

        @Override
        public void remove() {
            // TODO Auto-generated method stub

        }


    }

}
package coursera.week2.stackqueue;

public class QueueWithTwoStack<Item> {

    private  Stack<Item> inStack = new Stack<>();;
    private Stack<Item> outStack = new Stack<>();

    public boolean isEmpty() {
        return inStack.isEmpty() && outStack.isEmpty();
    } 

    public Item deQueue(){
        if(inStack.isEmpty()) {
            if(outStack.isEmpty()){
                System.out.println("error: now the queue is empty");
                return null;
            }
            else {
                moveElements();
            }
        }
        return inStack.pop();
    } 

    private void moveElements(){
        while( !outStack.isEmpty() ){
            inStack.push(outStack.pop());
        }
    }

    public void enQueue(Item item){
        outStack.push(item);
    } 
}

猜你喜欢

转载自blog.csdn.net/u014110320/article/details/77677242
今日推荐