zoukankan      html  css  js  c++  java
  • 自定义线性结构---栈

    /**
     * @desc:  栈结构-单链表实现
     * @author: 毛会懂
     * @create: 2020-12-29 18:03:00
     **/
    public class MyStack<T> implements Iterable<T>{
        private Node head; //头节点,指向栈顶,默认指向空
        private Integer count;//栈的大小
    
        public MyStack(){
            head = new Node(null,null);
            count = 0;
        }
    
        //进栈
        public void push(T t){
            Node node = new Node(t,head.next);
            head.next = node;
            count++;
        }
    
        //出栈
        public T pop(){
            if(head.next != null){
                Node node = head.next;
                head.next = node.next;
                count--;
                return node.t;
            }
            return null;
        }
    
        //是否空栈
        public Boolean isEmpty(){
            return count == 0;
        }
    
        //栈的大小
        public Integer size(){
            return count;
        }
    
        @Override
        public Iterator<T> iterator() {
            return new MyIterator(head);
        }
    
        private class MyIterator implements Iterator{
            private Node node;
    
            public MyIterator(Node head) {
                this.node = head;
            }
    
            @Override
            public boolean hasNext() {
                return node.next != null;
            }
    
            @Override
            public T next() {
                node = node.next;
                return node.t;
            }
        }
    
        private class Node{
            private T t;
            private Node next;
    
            public Node(T t, Node next) {
                this.t = t;
                this.next = next;
            }
        }
    }

    测试:

    public static void main(String[] args) {
    MyStack<Integer> myStack = new MyStack<>();
    myStack.push(10);
    myStack.push(20);
    System.out.println("第一次出栈:"+myStack.pop());
    System.out.println("栈的大小:" + myStack.size());
    System.out.println("栈是否为空:" + myStack.isEmpty());
    System.out.println("第一次遍历栈");
    for (Integer i : myStack){
    System.out.println(i);
    }
    System.out.println("第二次遍历栈");
    myStack.forEach(System.out::println);
    System.out.println("结束");
    System.out.println("第二次出栈:" + myStack.pop());
    System.out.println("第三次出栈:" + myStack.pop());
    }
  • 相关阅读:
    配置 Linux 服务器 SSH 安全访问的四个小技巧
    线性代数
    转载的其它人博客
    c#下dll引入错误的问题
    游戏中简单代码
    明年的任务
    c# 异步通信网络中存在的问题
    解决导入五万条数据缓慢问题
    c#中关于结构体和字节数组转化
    写给现在的自己
  • 原文地址:https://www.cnblogs.com/maohuidong/p/14216133.html
Copyright © 2011-2022 走看看