zoukankan      html  css  js  c++  java
  • [数据结构]手动实现栈

    栈有两种实现:静态栈(数组)和动态栈(链表)。这里采用链表。

    package com.darrenchan;
    
    public class MyStack {
        public ListNode stackTop;
        public ListNode stackBottom;
        public MyStack(ListNode stackTop, ListNode stackBottom){
            this.stackTop = stackTop;
            this.stackBottom = stackBottom;
        }
        /**
         * 进栈
         */
        public static void pushStack(MyStack myStack, int value){
            ListNode node = new ListNode(value);
            node.next = myStack.stackTop;
            myStack.stackTop = node;
        }
    
        /**
         * 遍历
         * 只要栈顶元素指针不指向栈底
         */
        public static void traverse(MyStack myStack){
            ListNode stackTop = myStack.stackTop;
            while(stackTop != myStack.stackBottom){
                System.out.print(stackTop.value + " ");
                stackTop = stackTop.next;
            }
            System.out.println();
        }
    
        /**
         * 判断是否为空
         */
        public static boolean isEmpty(MyStack myStack){
            if(myStack.stackTop == myStack.stackBottom){
                return true;
            }else{
                return false;
            }
        }
    
        /**
         * 出栈
         */
        public static void popStack(MyStack myStack){
            //栈不为空才出栈
            if(!isEmpty(myStack)){
                ListNode stackTop = myStack.stackTop;
                myStack.stackTop = stackTop.next;
                System.out.println(stackTop.value);
            }
        }
    
        /**
         * 清空栈
         */
        public static void clearStack(MyStack myStack){
            myStack.stackTop = null;
            myStack.stackBottom = myStack.stackTop;
        }
    
        public static void main(String[] args) {
            MyStack myStack = new MyStack(new ListNode(0), new ListNode(0));
            myStack.stackBottom = myStack.stackTop;
            //myStack.stackTop.next = null;
    
            System.out.println(isEmpty(myStack));
            //进栈
            pushStack(myStack, 1);
            pushStack(myStack, 2);
            pushStack(myStack, 3);
            traverse(myStack);
            System.out.println(isEmpty(myStack));
    
            popStack(myStack);
            clearStack(myStack);
            System.out.println(isEmpty(myStack));
        }
    }

  • 相关阅读:
    python libsvm模块在mac上的安装
    logistic regression (Python&Matlab实现)
    读C++ primer 的一些练习
    R笔记
    python学习笔记
    linux常用命令
    macbook air安装ubuntu双系统简记
    解方程——对分法
    解方程——不动点迭代
    隐马尔可夫模型模型评估及最优路径的matlab实现
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/9535549.html
Copyright © 2011-2022 走看看