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());
	}
}

链栈





你可能感兴趣的:(java)