1. 程式人生 > >下壓堆棧(鏈表實現)

下壓堆棧(鏈表實現)

list true urn div AC 元素 next 添加 定義

import java.util.Iterator;
public class Stack<Item>
{
    private Node first;   //棧頂
    private int N;        //元素數量
    private class Node
    {   //定義節點的嵌套類
        Item item;
        Node next;
    }
    public boolean isEmpty() {  return first == null; } // 或: N == 0
	public int size() {  return N; }
	public void push(Item item)
	{	// 向棧頂添加元素
		Node oldfirst = first;
		first = new Node();
		first.item = item;
		first.next = oldfirst;
		N++;
	}
	public Item pop()
	{	//從棧頂刪除元素
		Item item = first.item;
		first = first.next;
		N--;
		return item;
	}
	public Iterator<Item> iterator()
	{	return new ListIterator();	}
	private class ListIterator implements Iterator<Item>
	{
		private Node current = first;
		public boolean hasNext()
		{	return current != null;	}
		public void remove() { }
		public Item next()
		{
			Item item = current.item;
			current = current.next;
			return item;
		}
	}       
}

  

下壓堆棧(鏈表實現)