java定义堆栈_java自定义堆栈

package com.zhb.corejava.util;

public class Stack {

private E[] elementData;

private int top;

private int count;

@SuppressWarnings("unchecked")

public Stack(int size) {

this.elementData = (E[]) new Object[size];

top = -1;

count = 0;

}

public Stack() {

this(10);

}

/**

* 返回堆栈长度

* @return

*/

public int getSize(){

return elementData.length;

}

/**

* 返回栈中元素的个数

* @return

*/

public int getElementCount() {

return count;

}

/**

* 判栈空

* @return

*/

public boolean isEmpty(){

return top == -1;

}

/**

* 判栈满

* @return

*/

public boolean isFull(){

return top == (elementData.length-1);

}

/**

* 入栈操作

* @param object

*/

public void push(E object){

if(isFull()){

throw new RuntimeException("栈已经满");

}else{

elementData[++top] = object;

count++;

}

}

/**

* 出栈操作,并返回被出栈的元素

* @return

*/

public E pop(){

if(isEmpty()){

throw new RuntimeException("栈是空的");

}else{

count--;

return elementData[top--];

}

}

/**

* 返回栈顶元素

* @return

*/

public E peek(){

if(isEmpty()){

throw new RuntimeException("栈是空的");

}else{

return elementData[top];

}

}

}

编写测试类:

package com.zhb.corejava.util;

public class ClientTest {

public static void main(String[] args) {

Stack stack = new Stack();

User user1 = new User("张三", 1);

User user2 = new User("李四", 2);

User user3 = new User("王五", 2);

stack.push(user1);

stack.push(user2);

stack.push(user3);

System.out.println("stack.size====" + stack.getSize());

User user = stack.pop();

System.out.println("user.name==1==" + user.getName());

System.out.println("-------------------------------------------");

user = stack.pop();

System.out.println("user.name==2==" + user.getName());

System.out.println("-------------------------------------------");

user = stack.pop();

System.out.println("user.name==3==" + user.getName());

System.out.println("stack.size====" + stack.getSize());

System.out.println("-------------------------------------------");

stack.push(user1);

System.out.println("stack.size====" + stack.getSize());

System.out.println("stack.isEmpty==="+stack.isEmpty());

System.out.println("stack.isFull==="+stack.isFull());

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值