zoukankan      html  css  js  c++  java
  • 【数据结构与算法之美】2.基于链表实现的栈

    package com.ncst.stack;
    
    /**
     * @author i
     * @create 2019/12/19 20:56
     * @Description 基于链表实现栈
     */
    public class StackBasedOnLinkedList<T>{
    
        private Node top;//设置一个top 用来标记栈顶
    
        //出栈
        public void push(int value) {
            Node newNode = new Node(value, null);
            if (top == null) {
                top = newNode;
                return;
            }
            newNode.next = top;//将newNode的next设置为top
            top = newNode;//将newNode设置为栈顶结点
        }
    
        //入栈
        public T pop(){
            if (top == null){
                throw  new NullPointerException("statck is empty!");
            }
            T value = (T) top.data;
            top = top.next;
            return value;
        }
    
        //打印
        public void printfAll(){
            if (top == null){
                return;
            }
    
            Node cur = top;
            while (cur!=null){
                System.out.print(cur.data+",");
                cur = cur.next;
            }
        }
    
        public static void main(String[] args) {
            StackBasedOnLinkedList s = new StackBasedOnLinkedList();
            s.push(1);
            s.push(2);
            s.push(3);
    
            System.out.println(s.pop());
            System.out.println(s.pop());
            System.out.println(s.pop());
    
        }
    
        //创建节点
        private class Node<T> {
            private T data;
            private Node next;
    
            public Node(T data, Node next) {
                this.data = data;
                this.next = next;
            }
    
            public T getData() {
                return data;
            }
    
            public Node getNext() {
                return next;
            }
    
        }
    
    }
    
  • 相关阅读:
    6-stm32 滴答定时器(delay不带中断延时)
    5-stm32 滴答定时器(delay中断延时)
    4- stm32 gpio重映射
    3- stm32 gpio寄存器
    2-stm32 gpio位带
    Linux Command
    DIV+CSS规范命名
    JS事件报错之Cannot set property 'onclick' of null
    创建对象的三种方式
    密码的显示和隐藏
  • 原文地址:https://www.cnblogs.com/qxlxi/p/12860749.html
Copyright © 2011-2022 走看看