【Java】一个数组实现三个栈 (未完待续)

来源:互联网 发布:2017优化六上数学答案 编辑:程序博客网 时间:2024/05/17 03:52

等长的相对简单,设置三个栈顶指针,考虑栈为空的情况分别push和pop就好

public class threeStacks {int stackSize = 100;int[] buffer = new int[ stackSize * 3 ];int[] stackPointer = {-1, -1, -1}; //pointer to trace the stack element number in every stackvoid push(int stackNum, int value) throws Exception {//check if there's free spaceif (stackPointer[stackNum] + 1 >= stackSize) { //the last elementthrow new Exception ("Out of space!");}//stack pointer increases, update the top element valuestackPointer[stackNum]++;buffer[absTopOfStack(stackNum)] = value;}int pop(int stackNum) throws Exception {if ( -1 == stackPointer[stackNum] ) {throw new Exception ("Trying to pop an empty stack!");}int value = buffer[absTopOfStack(stackNum)];buffer[absTopOfStack(stackNum)] = 0; //mark as 0stackPointer[stackNum]--;return value;}int peek(int stackNum) {int index = absTopOfStack(stackNum);return buffer[index];}boolean isEmpty(int stackNum) {return stackPointer[stackNum] == -1;}//return the top element's absolute index in buffer[]int absTopOfStack(int stackNum) {return stackNum * stackSize + stackPointer[stackNum];}}


变长的比较复杂, 未完待续

0 0
原创粉丝点击