关闭

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

473人阅读 评论(0) 收藏 举报
分类:

等长的相对简单,设置三个栈顶指针,考虑栈为空的情况分别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 stack
	
	void push(int stackNum, int value) throws Exception {
		//check if there's free space
		if (stackPointer[stackNum] + 1 >= stackSize) { //the last element
			throw new Exception ("Out of space!");
		}
		
		//stack pointer increases, update the top element value
		stackPointer[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 0
		stackPointer[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
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:127227次
    • 积分:3165
    • 等级:
    • 排名:第11490名
    • 原创:180篇
    • 转载:107篇
    • 译文:0篇
    • 评论:10条
    文章分类
    最新评论