包含min函數的棧(不算巧妙 從數據結構下手)

我剛開始是想使用LinkedList實現,牛客不讓用java的集合,就沒用了
想着不讓用LinkedList,我就只能自定義一個List了
本着不麻煩夠用就行的原則,寫了個單鏈表。算法上沒有有點 單純的判斷。
後來看題解,牛客可以用Stack集合,我暈,給個提示啊,能用什麼不能用什麼,讓我大費周折!

private static class MyStack {
        private Node head;
        private int minValue;

        private static class Node {
            Node next;
            int value;

            Node(int value) {
                this.value = value;
            }

            Node(int value, Node next) {
                this.value = value;
                this.next = next;
            }
        }

        public void push(int node) {
            if (head == null) {
                head = new Node(node);
                minValue = node;
            } else {
                head = new Node(node, head);
                // 插入元素比最小值小 就替換最小值
                minValue = minValue < node ? minValue : node;
            }
        }

        public void pop() {
            if (head == null) {
                return;
            }
            // 將頭節點指向下個節點
            int headValue = head.value;
            head = head.next;
            // 如果移除的數字和最小值相等 就要尋找最小值了
            if (headValue == minValue) {
                Node n = head;
                // 沒有節點了 重置最小值
                if (n == null) {
                    minValue = 0;
                    return;
                }

                // 將頭節點值賦給最小值 依次和後面比較
                minValue = n.value;
                while (n != null) {
                    minValue = minValue < n.value ? minValue : n.value;
                    n = n.next;
                }
            }
        }

        public int top() {
            if (head != null) {
                return head.value;
            }
            return -1;
        }

        public int min() {
            return minValue;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章