1. 程式人生 > >資料結構 -- 鏈棧java實現

資料結構 -- 鏈棧java實現

資料結構--鏈棧  java 實現

1.鏈棧,top指向棧頂元素。順序棧,和 IStack 介面在這點選開啟連結

//節點的定義  
class Node{  
    public Object data;  
    public Node next;  
    //無參構造方法  
    public Node(){  
        this(null,null);  
    }  
    //一個引數的構造方法  
    public Node(Object data){  
        this(data,null);  
    }  
    //兩個引數的構造方法  
    public Node(Object data, Node next){  
        this.data = data;  
        this.next = next;  
    }  
}  
//鏈棧類
public class LinkStack implements IStack{
	
	private Node top;	//指向棧頂元素,空棧時為null
	
	//置空棧
	@Override
	public void clear() {
		// TODO Auto-generated method stub
		top = null;
	}
	
	//判斷棧是否為空
	@Override
	public boolean isEmpty() {
		// TODO Auto-generated method stub
		return top == null;
	}
	
	//查詢棧頂元素
	@Override
	public Object peek() {
		// TODO Auto-generated method stub
		if(!isEmpty())
			return top.data;
		return null;
	}

	//鏈棧的長度
	@Override
	public int length() {
		// TODO Auto-generated method stub
		Node p = top;
		int length = 0;
		while(p != null){
			length++;
			p = p.next;
		}
		return length;
	}

	//元素入棧
	@Override
	public void push(Object x) {
		// TODO Auto-generated method stub
		Node p = new Node(x);
		p.next = top;
		top = p;
	}

	//棧頂元素出棧
	@Override
	public Object pop() {
		// TODO Auto-generated method stub
		if(isEmpty()){
			return null;
		}
		Node p = top;
		top = top.next;
		return p.data;
	}
/*
 * 測試用,忽略
 */
//	public static void main(String[] args) throws Exception{
//		LinkStack mystack = new LinkStack();
//		mystack.push(1);
//		mystack.push(2);
//		mystack.push(3);
//		mystack.push(4);
//		mystack.push(5);
//		System.out.println(mystack.length());
//		System.out.println(mystack.isEmpty());
//		System.out.println(mystack.peek());
//		for(int i=0;i<5;i++){
//			System.out.println(mystack.pop());
//		}
//		System.out.println(mystack.isEmpty());
//		System.out.println(mystack.length());
//	}
}