猿辅导面试算法题(7:一个数组实现两个栈)

一、原理

定义一个数组,由两个指针分别指向数组的首部和尾部,其分别代表两个栈的栈顶
猿辅导面试算法题(7:一个数组实现两个栈)_第1张图片

二、代码实现

package com.jp.yuanfudao.prepare.mianshi.test7;

/**
 * @program: mianjing
 * @description: 一个数组实现两个栈
 * @author: CoderPengJiang
 * @create: 2020-06-26 18:58
 **/
public class Main {
    public static void main(String[] args) {
        DoubleStack doubleStack=new DoubleStack(8);
        doubleStack.push1(1);
        doubleStack.push1(3);
        doubleStack.push1(4);
        doubleStack.push1(5);
        doubleStack.push2(9);
        doubleStack.push2(8);
        doubleStack.push2(7);
        doubleStack.push2(6);
        doubleStack.print_stack1();
        doubleStack.print_stack2();
        System.out.println(doubleStack.getLength());
    }
}

class DoubleStack {
    //两个栈的长度
    private int length;
    private int top1,top2;
    private int[] array;

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getTop1() {
        return top1;
    }

    public void setTop1(int top1) {
        this.top1 = top1;
    }

    public int getTop2() {
        return top2;
    }

    public void setTop2(int top2) {
        this.top2 = top2;
    }

    public int[] getArray() {
        return array;
    }

    public void setArray(int[] array) {
        this.array = array;
    }

    public DoubleStack(int length) {
        this.length = length;
        array=new int[length];
        top1=-1;
        top2=length;
    }
    //定义两个栈的push和pop
    public boolean push1(int a){
        if (top1+1==top2){
            return false;
        }else{
            array[++top1]=a;
            return true;
        }
    }

    public boolean push2(int a){
        if (top2-1==top1){
            return false;
        }else {
            array[--top2]=a;
            return true;
        }
    }

    public boolean pop1(){
        if (top1==-1){
            return false;
        }else {
            top1--;
            return true;
        }
    }

    public boolean pop2(){
        if (top2==length){
            return false;
        }else {
            top2--;
            return true;
        }
    }

    public void print_stack1(){
        if (top1==-1){
            System.out.println(
                    "stack1 is empty!!!"
            );
        }else {
            for (int i=0;i<=top1;i++){
                System.out.print(array[i]+" ");
            }
            System.out.println();
        }
    }

    public void print_stack2(){
        if (top2==length){
            System.out.println(
                    "stack2 is empty!!!"
            );
        }else {
            for (int i=length - 1;i>=top2;i--){
                System.out.print(array[i]+" ");
            }
            System.out.println();
        }
    }
}

你可能感兴趣的:(算法,面经)