栈的实现与用栈实现队列

栈的实现

/**
 * 栈的实现:数组
 */
class MyStack1<T>{
    private T[] data;
    private int maxLength;
    private int top;

    public MyStack1(int maxLength) {
        this.maxLength = maxLength;
        this.data= (T[])new Object[maxLength];
        top=-1;
    }

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

    public boolean push(T t){
        if(!isFull()) {data[++top]=t;return true;}
        return false;
    }
    public T pop(){
        if(!isEmpty()){return data[top--];}
        return null;
    }
}

/**
 * 栈的实现:链表(插入到链表头,并从头取)
 */
class MyStack2<T>{
    private Node<T> head;
    private int size;
    private int maxSize;
    private class Node<T>{
        private T data;
        private Node<T> next;

        public Node(T data) {
            this.data = data;
        }
    }

    public MyStack2(int maxSize) {
        this.maxSize = maxSize;
    }

    public boolean isEmpty(){
        if(size<=0)return true;
        return false;
    }
        public boolean isFull(){
        if(size>=maxSize)return true;
        return false;
    }
    public boolean push(T t){
        if(!isFull()){
            Node node = new Node(t);
            node.next=head;
            head=node;
            size++;
        }
        return false;
    }
    public T pop(){
        if(!isEmpty()){
            T data = head.data;
            head=head.next;
            size--;
            return data;
        }
        return null;
    }
}

使用栈实现队列

/**
 *使用栈实现队列的下列操作:
 *
 * push(x) -- 将一个元素放入队列的尾部。
 * pop() -- 从队列首部移除元素。
 * peek() -- 返回队列首部的元素。
 * empty() -- 返回队列是否为空。
 */
class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    /** Initialize your data structure here. */
    public MyQueue() {
        this.stack1 = new Stack();
        this.stack2 = new Stack();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(!empty()){
            if(!stack2.empty())return stack2.pop();
            while(!stack1.empty())stack2.push(stack1.pop());
        }
        return stack2.pop();
    }

    /** Get the front element. */
    public int peek() {
        if(!empty()){
            if(!stack2.empty())return stack2.peek();
            while(!stack1.empty())stack2.push(stack1.pop());
        }
        return stack2.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        if(stack1.empty() && stack2.empty())return true;
        return false;
    }
}

猜你喜欢

转载自www.cnblogs.com/loveer/p/11757359.html