java实现stack

1.使用链表实现stack
class stacknode
{
public stacknode(int d) {
// TODO Auto-generated constructor stub
this.data = d;
}
public int data;
public stacknode nextnode;
}
   public class stackBylink {
public static void main(String[] args) {
stackBylink stackBylink = new stackBylink();
}
//每次加入新的节点都将新的元素插入到第一个位置表示进栈的操作
private stacknode top;
int size = 0;
public stackBylink()
{
top = null;
}
public int getStackSize()
{
return this.size;
}
public void showStack()
{
stacknode tmp = top;
while (tmp!=null)
{
System.out.println(tmp.data);
tmp = tmp.nextnode;
}
}


public void push(int e)
{
stacknode tmpnode = new stacknode(e);
this.size++;
if(top==null)
{
top = tmpnode;
}
else
{
tmpnode.nextnode = top;
top = tmpnode;
}
}
public void pop()
{
if(isEmpty())
{
return;
}
top = top.nextnode;

}
public boolean isEmpty()
{
if(top==null)
{
System.out.println("the stack has been empty");
return true;
}
return false;
}

}

2.使用数组实现stack

public class stackbydefine{

public static void main(String[] args) {
stackbydefine stack = new  stackbydefine(1024);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.getStackLocation());
stack.showStack();
}
     //数组实现栈,一个栈顶top
private int top;
private int capacity;
private int[]array;
public void showStack()
{
for (int i = 0; i <= top; i++) {
System.out.println(array[i]);
}
}
public int getStackLocation()
{
return top;
}
public stackbydefine(int capacity) {
top =-1;
this.capacity  =capacity;
this.array = new int [capacity];
}
public void push(int e)
{
top++;
if(isFull())
{
System.out.println("ths stack is full");
return;
}
array[top]=e;
}
public void pop()
{
if(isEmpty())
{
System.out.println("ths stack is empty");
return;
}

}
public boolean isFull()
{
if(top==capacity-1)
{
return true;
}
return false;
}
public boolean isEmpty()
{
if(top==-1)
{
return true;
}
return false;
}
public void enhanceCapacity()
{
//当发现栈的已经full的时候可以进行扩容,此处方法是截止将栈的容量扩充为2倍,此方发的好处是能够降低重新生成数组的空间复杂度
int []newarray = new int[capacity*2];
System.arraycopy(array,0,newarray,0,capacity);
capacity *= 2;
array = newarray;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值