单链表实现栈的链式存储结构

package com.myTest.stack;

/**
 * 单链表实现栈的链式存储结构
 *
 * @param <T>
 */
public class LinkStack<T> {
    public static void main(String[] args) {
        LinkStack<Integer> linkStack = new LinkStack<>();
        linkStack.push(1);
        linkStack.push(2);
        linkStack.push(3);
        linkStack.push(4);
        linkStack.push(5);
        linkStack.push(6);
        System.out.println(linkStack);

        System.out.println(linkStack.pop());
        System.out.println(linkStack+ " 元素个数:"+linkStack.size());

        linkStack.push(8);
        linkStack.push(10);
        System.out.println(linkStack+ "元素个数:"+linkStack.size());


    }

    //栈顶节点
    private Node<T> preFirst;
    //栈当前空间大小
    private static int size = 0;

    public int size() {
        return size;
    }

    /**
     * 栈节点
     *
     * @param <T>
     */
    public static class Node<T> {
        Node<T> next;
        T data;

        public Node(T e, Node<T> nextNode) {
            this.next = nextNode;
            this.data = e;
        }

        private Node() {
        }
    }

    /**
     * 压栈,不断从头结点插入元素
     *
     * @param e 元素
     */
    public synchronized void push(T e) {
        if (preFirst == null) {
            preFirst = new Node(e, null);
        } else {
            preFirst = new Node(e, preFirst);
        }
        size++;
    }

    /**
     * 弹栈
     *
     * @return 返回栈顶元素
     */
    public synchronized T pop() {
        T data = null;
        if (preFirst != null) {
            Node<T> oldNode=preFirst;
            data = oldNode.data;
            if (preFirst.next != null) {
                //从头结点开始下移
                preFirst = preFirst.next;
            } else {
                preFirst = null;
            }
            oldNode.next=null;
            size--;
        }
        return data;
    }

    @Override
    public String toString() {
        String result = "[";
        Node<T> currentNode = preFirst;
        while (currentNode != null) {
            result = result + "," + currentNode.data;
            currentNode = currentNode.next;
        }
        result = result.replaceFirst(",", "");
        result = result + "]";
        return result;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值