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

栈的思想。

我再想想!~~~~

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();
    }


}

 

相关文章:

  • 2021-05-15
  • 2021-12-19
  • 2021-10-28
  • 2022-12-23
  • 2021-11-23
  • 2021-06-13
  • 2021-05-07
  • 2022-01-28
猜你喜欢
  • 2021-11-04
  • 2021-11-19
  • 2022-12-23
  • 2021-09-08
  • 2021-07-22
  • 2022-12-23
  • 2021-06-13
相关资源
相似解决方案