java用單鏈表實現棧的基本操作


package Eric.ADT;

/**
 * <p>
 * Title:MyStack
 * </p>
 * <p>
 * Description:用單鏈表實現棧的基本操作
 * </p>
 * <p>
 * Location:Frostburg
 * </p>
 * 
 * @author: Eric.Chen
 * @date:2017年9月24日下午7:31:28
 */
public class MyStack {
    class Node {// 定義節點
        private Node next;
        public Object value;
    }

    Node top = null;

    void init() {//初始話頭結點
        top = new Node();
        top.next = null;
        top.value = null;
    }

    public void push(Object element) {//采用頭插發的方式模擬入棧
        Node e = new Node();
        e.value = element;
        if (top.next == null) {
            top.next = e;
        } else {
            e.next = top.next;
            top.next = e;

        }

    }

    public Object pop() {//彈出棧頂元素,也就是頭結點后面的第一個元素
        Object ele = null;
        if (top.next == null) {
            System.out.println("棧為空!");
        } else {
            ele = top.next.value;
            top.next = top.next.next;//移動指針。相當於刪除鏈表中第一個元素
        }
        return ele;
    }
 
    public Object peek()//返回棧頂元素,不執行出棧操作
    {
        if(top.next==null)
        {
            return -1;
        }
        else
        return top.next.value;
    }
    public boolean isempty()//判斷棧是否為空
    {
        return top.next==null?true:false;
    }
    public int size() {//返回棧的大小,含有的元素個數
        Node temp = top;
        int i = 0;
        while (temp.next != null) {
            i++;
            temp = temp.next;
        }
        return i;
    }

    public void print() {//打印棧中存在的元素
        Node temp = top;
        if(temp.next==null)
        {
            System.out.println("棧為空!");
        }
        while (temp.next != null) {
            System.out.print(temp.next.value + "  ");
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.init();
        for (int i = 0; i < 5; i++) {
            stack.push(i);
        }
        /*Object ele1 = stack.pop();
        Object ele2 = stack.pop();
        Object ele3 = stack.pop();
        Object ele4 = stack.pop();
        Object ele5 = stack.pop();
        System.out.println(ele1);
        System.out.println(ele2);
        System.out.println(ele3);
        System.out.println(ele4);
        System.out.println(ele5);*/
        Object ele1 = stack.pop();
        System.out.println("此次彈出的元素為:"+ele1);
        System.out.print("棧中剩余的元素為:");
        stack.print();
        System.out.println();
        System.out.println("棧頂元素為:"+stack.peek());
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM