[数据结构]-单链表实现栈

单链表实现栈,是实现了,但是好像思想不是那么对。

栈的思想。

我再想想!~~~~

package com.cn.jichu.day08;

public class LinkedStack<E> {

    private class Node{
        private Node next;
        private E data;

        public Node(E data) {
            this.data = data;
        }

    }

    private Node head;

    public LinkedStack() {
    }

    /**
     * 入栈
     * @param e
     */
    public void push(E e){
        Node node = new Node(e);
        if(head == null){
            head = node;
        }else{
            node.next = head;
            head = node;
        }
    }

    /**
     * 出栈
     * @return
     */
    public E pop(){
        if(head == null){
            throw  new IllegalArgumentException("栈中没有元素");
        }
        Node prev = head.next;
        E e = head.data;
        head = prev;
        return e;
    }

    /**
     * 获取栈顶元素
     * @return
     */
    public E peek(){
        if(head == null){
            throw  new IllegalArgumentException("栈中没有元素");
        }
        return head.data;
    }


    @Override
    public String toString(){
        StringBuilder stringBuilder = new StringBuilder();
        Node cur = head;
        stringBuilder.append("stock:[");
        while (cur!=null){
            stringBuilder.append(cur.data + " ");
            cur = cur.next;
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }


}
原文地址:https://www.cnblogs.com/anny0404/p/10653325.html