• [数据结构]手动实现栈


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

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

  • 相关阅读:
    LeetCode 27. Remove Element(C++)
    LeetCode 26. Remove Duplicates from Sorted Array
    LeetCode 21. Merge Two Sorted Lists(c++)
    LeetCode 20. Valid Parentheses(c++)
    LeetCode 14.Longest Common Prefix(C++)
    poj1847 Tram(最短路dijkstra)
    poj 3268 Silver Cow Party(最短路dijkstra)
    LeetCode 13. Roman to Integer(c语言版)
    hdu2181 简单搜索
    python 算法 day1
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/9535549.html
Copyright © 2020-2023  润新知