猿輔導面試算法題(7:一個數組實現兩個棧)

一、原理

定義一個數組,由兩個指針分別指向數組的首部和尾部,其分別代表兩個棧的棧頂
在這裏插入圖片描述

二、代碼實現

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();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章