使用数组实现的自定义栈结构

package com.hebtu.java.vector;

/**
 * 自定义的 栈 结构
 * @author Xmh
 *
 */
public class MyStack {
	private int maxSize; //栈的大小
	private long[] stackArray; 
	private int top; //栈顶
	
	public MyStack(int s) {
		maxSize = s; // 设置栈的大小
		stackArray = new long[maxSize]; //创建一个数组
		top = -1; //top:-1 表示栈中还没有元素
	} 
	
	/**
	 * 压栈
	 */
	public void push(long j){
		//stackArray[++top] = j;
		stackArray[top+1] = j;
		top = top + 1;
	}
	
	/**
	 * 出栈
	 * @return
	 */
	public long pop(){
		//long j = stackArray[top--];
		long j = stackArray[top];
		top = top -1;
		return j;
	}
	
	/**
	 * 取栈顶元素
	 */
	public long peek(){
		return stackArray[top];
	}
	
	/**
	 * 是否为空
	 * @return
	 */
	public boolean isEmpty(){
		if(top == -1){
			return true;
		}
		return false;
	}
	
	/**
	 * 是否为满栈
	 * @return
	 */
	public boolean isFull(){
		if(top == maxSize-1){
			return true;
		}
		return false;
	}
}

以下是对MyStack.java进行测试的类
<pre name="code" class="java">package com.hebtu.java.vector;

import org.junit.Test;

public class MyStackTest {
	
	public static MyStack myStack = null;
	public static int max = 10;
	{
		myStack = new MyStack(max);		
	}
	
	@Test
	public void testPush() {
		myStack.push(10);
		myStack.push(20);
		myStack.push(50);
		myStack.push(30);
		myStack.push(40);
		while(!myStack.isEmpty()){
			long value = myStack.pop();
			System.out.println(value);
		}
	}

	@Test
	public void testPop() {
		
	}
	
	/**
	 * 测试 使用栈对单词进行倒序输出
	 */
	@Test
	public void testReverser(){
		String word = "HelloWorld Stack";
		MyStack stack = new MyStack(word.length());
		for(int i=0;i<word.length();i++){
			char c = word.charAt(i);
			stack.push(c);
		}
		while(!stack.isEmpty()){
			char s = (char) stack.pop();
			System.out.print(s);
		}
		
	}

}


 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值