栈(Java链式实现)

/**
 * 链式栈的实现
 * 相当于只能在头部插入和删除的单链表
 */
public class LinkedStack
{
    private static final String TAG = "LinkedStack";
    /*长度和头指针*/
    private int size = 0;
    private StackNode top = null;//top

    /*节点类*/
    class StackNode
    {
        Object value;
        StackNode next = null;

        StackNode(Object obj)
        {
            this.value = obj;
        }
    }


    public void push(Object obj)
    {
        StackNode snode = new StackNode(obj);
        snode.next = top;
        top = snode;
        size++;
    }

    public Object pop() throws Exception
    {
        if (top == null) throw new Exception("空栈!");
        Object obj = top.value;
        top = top.next;
        size--;
        return obj;
    }

    public int getSize()
    {
        return size;
    }

    public boolean isEmpty()
    {
        return top == null;
    }

    public void display() throws Exception
    {
        if (top == null) throw new Exception("空栈!");
        StackNode cur = top;
        while (cur != null)
        {
            System.out.print(cur.value.toString() + "->");
            cur = cur.next;
        }
    }

    public static void main(String[] args) throws Exception
    {
        LinkedStack lk = new LinkedStack();
        //lk.pop();
        //lk.display();
        lk.push("你好");
        lk.push("qeqwe");
        lk.push("rrr");
        lk.push("htht");
        lk.push("5655");
        lk.push("你");
        lk.push("好");
        lk.display();
        System.out.println("\n" + lk.getSize());
        lk.pop();
        lk.pop();
        lk.pop();
        lk.display();
        System.out.println("\n" + lk.getSize());


    }


} 
posted @ 2016-09-09 21:59  带妳心菲  阅读(127)  评论(0编辑  收藏  举报
Live2D
jQuery火箭图标返回顶部代码