1. 程式人生 > 實用技巧 >2011_線性表之棧

2011_線性表之棧

2.3 棧

棧是一種基於先進後出的資料結構, 是一種只能在一端進行插入和刪 除操作的特殊線性表. 它按昭先進後出的原則儲存資料, 先進入的資料被壓入棧底, 最後的資料在棧頂, 需要讀資料的時候從棧頂開始彈出資料.

我們稱資料進入到棧的動作為壓棧, 資料從棧中出去的動作為彈棧

2.3.1API設計

類名 Stack
構造器 Stack()
成員方法 1. public boolean isEmpty();判斷棧是否為空
2. public int size(); 獲取棧中元素的個數
3. public T pop();彈出棧頂元素
4. public voi pust();壓棧
成員變數 1. private Node head;
2. private int N;
成員內部類 private class Node;

2.3.2 棧程式碼的實現

package b_linear.c_stack;

import java.util.Iterator;

/**
 * 棧
 */
public class Stack<T> implements Iterable{
    //成員變數
    private Node head;
    private int N;



    private class Node{
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public Stack(){
        this.head = new Node(null, null);
        this.N = 0;
    }

    //判斷元素個數是否為0
    public boolean isEmpty(){
        return N == 0;
    }

    //獲取棧中元素的個數
    public int size(){
        return N;
    }

    //壓棧
    public void pust(T t) {
        //找到head指向的第一個結點
        Node oldFirst = head.next;
        //建立新結點
        Node newNode = new Node(t, null);

        //首結點指向新結點
        head.next = newNode;

        //新結點指向原來的第一個結點
        newNode.next = oldFirst;

        //元素個數+1
        N++;
    }

    //彈棧
    public T pop() {
        //找到head指向的第一個結點
        Node oldFirst = head.next;

        if(oldFirst == null) {
            return null;
        }
        //讓head指向原來第一個節結的下一個結點
        head.next = oldFirst.next;

        //元素個數-1
        N--;
        return oldFirst.item;
    }

    @Override
    public Iterator iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator {
        private Node n;
        public SIterator() {
            this.n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }
}

2.3.3 測試

package b_linear.c_stack;

/**
 * 棧測試
 */
public class StackTest {
    public static void main(String[] args) {
        //建立棧物件
        Stack<String> stack = new Stack<>();
        //壓棧
        stack.pust("a");
        stack.pust("b");
        stack.pust("c");
        stack.pust("d");
        for(Object item : stack) {
            System.out.println((String)item);
        }
        System.out.println("------------");
        //彈棧
        String result = stack.pop();
        System.out.println("彈出的元素:" + result);
        System.out.println("剩餘元素個數: " + stack.size());
    }
}

測試結果

d
c
b
a
------------
彈出的元素:d
剩餘元素個數: 3