cci-Q3.1 一个数组实现三个栈

来源:互联网 发布:linux war解压 编辑:程序博客网 时间:2024/05/16 05:23

原文:

Describe how you could use a single array to implement three stacks.

译文:

你如何只用一个数组实现三个栈?

根据栈的大小,申请一个3*stacksize的数组。

public class stack3 {    int[] buffer = null;    int size = 0;    int[] stackpt = {-1, -1, -1};    public stack3(int size) {        this.size = size;        this.buffer = new int[this.size * 3];    }    boolean push(int stackNum, int value) {        if (stackpt[stackNum] > size - 2) {            return false;        }        int index = stackNum * this.size + stackpt[stackNum] + 1;        stackpt[stackNum]++;        buffer[index] = value;        return true;    }    int pop(int stackNum) {        if (this.stackpt[stackNum] < 0) {            return Integer.MIN_VALUE;        }        int index = stackNum * this.size + stackpt[stackNum];        stackpt[stackNum]--;        int val = buffer[index];        buffer[index] = 0;        return val;    }    int peek(int stackNum) {        if (this.stackpt[stackNum] < 0) {            return Integer.MIN_VALUE;        }        int index = stackNum * this.size + stackpt[stackNum];        return buffer[index];    }    boolean isEmpty(int stackNum) {        return stackpt[stackNum] == -1;    }}

testcase

 public static void main(String args[]) {        stack3 stack = new stack3(20);        for (int i = 0; i < 20; i++) {            stack.push(0, i);        }        for (int i = 0; i < 10; i++) {            System.out.println(stack.pop(0));        }        System.out.println(stack.pop(1));        System.out.println(stack.isEmpty(2));        System.out.println(stack.peek(0));    }