Java鏈表與數組實現棧

public class LinkStack<T> {
	Node<T> top;
	private int mSize;
	
	public LinkStack() {

	}
	
    boolean addNode(Node<T> node){
		if(node == null){
			return false; 
		}
		if (top == null) {
			top = node;
		}else {
			node.next = top;
			top = node;
		}
		mSize++;
		return true;
	}
    Node<T> popNode() throws Exception{
  		if(mSize == 0){
  			throw new Exception("has no node can be poped");
  		}
  		Node<T> currentNode = top;
  		top = top.next;
  		mSize--;
  		currentNode.next = null;
  		return currentNode;
  		
  	}

	public int getSize() {
		return mSize;
	}

	public boolean isEmpty(){
		return mSize == 0 ? true : false;
	}
}
class ArrayStack<T>{
	  T[] stack;
	  int mMax;
	  int mSize;
	  public ArrayStack(int max) {
		  mMax = max;
		  stack = (T[]) new Object[mMax];
	  }
	  boolean addNode(Node<T> node){
			if(node == null){
				return false; 
			}
			if(mSize == mMax){
				stack = Arrays.copyOf(stack, mMax * 2);
				mMax *= 2;
			}
			stack[mSize] = (T) node;
			mSize++;
			return true;
		}
	    Node<T> popNode() throws Exception{
	  		if(mSize == 0){
	  			throw new Exception("has no node can be poped");
	  		}
	  		Node<T> currentNode = (Node<T>) stack[mSize - 1];
	  		mSize--;
	  		return currentNode;
	  		
	  	}

		public int getSize() {
			return mSize;
		}

		public boolean isEmpty(){
			return mSize == 0 ? true : false;
		}
}

class Node<T>{
	  T data;
	  Node<T> next;
	  public Node(T data) {
		  this.data = data;
	  }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章