stack的java实现


import java.lang.Exception;

class MyStack
{
private static final int MAX_SIZE = 5;
private int[] t = new int[MAX_SIZE];
private int top = -1;

public void push(int x) throws Exception{

if(isFull()){
throw new Exception("栈已满");
}else{
t[++top] = x;
}

}

public int pop() throws Exception{

if(isEmpty()){
throw new Exception("栈为空");
}else{
return t[top--];
}
}

public boolean isFull(){
return top == MAX_SIZE - 1;
}

public boolean isEmpty(){
return top == -1;
}

public void printStack(){
for(int i = 0; i <= top; i++){
System.out.print(t[i]);
}
}
}

public class Temp
{
public static void main(String[] args) throws Exception{
MyStack ms = new MyStack();
ms.push(1);
ms.push(2);
ms.push(3);
ms.push(4);
ms.push(5);
System.out.println(ms.pop());
//ms.push(6);
ms.printStack();
}
}

顺序栈


class Node
{
public int data;
public Node next;

public Node(int data){
this.data = data;
}
}

class LinkedStack
{
private Node head;

public void push(int a){
Node node = new Node(a);
if(head == null){
head = node;
}else{
node.next = head;
head = node;
}
}

public int pop() throws Exception{
if(isEmpty()){
throw new Exception("栈为空");
}else{
Node temp = head;
head = head.next;
return temp.data;
}

}

public boolean isEmpty(){
return head == null;
}
}

public class TestLinkedStack
{
public static void main(String[] args) throws Exception{
LinkedStack ls = new LinkedStack();
ls.push(3);
ls.push(4);
System.out.println(ls.pop());
System.out.println(ls.pop());
//System.out.println(ls.pop());
}
}

链栈
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值