1栈和队列--设计一个有getMin功能的栈

来源:互联网 发布:精算 知乎 编辑:程序博客网 时间:2024/06/06 15:43
实现功能:

- 正常压栈
- 正常弹栈
- 返回栈中最小值

方法1:
这里写图片描述

public void push(int newNum) {            if (this.stackMin.isEmpty()) {                this.stackMin.push(newNum);            } else if (newNum <= this.getmin()) {                this.stackMin.push(newNum);            }            this.stackData.push(newNum);        }        public int pop() {            if (this.stackData.isEmpty()) {                throw new RuntimeException("Your stack is empty.");            }            int value = this.stackData.pop();            if (value == this.getmin()) {                this.stackMin.pop();            }            return value;        }        public int getmin() {            if (this.stackMin.isEmpty()) {                throw new RuntimeException("Your stack is empty.");            }            return this.stackMin.peek();        }

方法2:
这里写图片描述

public void push(int newNum) {            if (this.stackMin.isEmpty()) {                this.stackMin.push(newNum);            } else if (newNum < this.getmin()) {                this.stackMin.push(newNum);            } else {                int newMin = this.stackMin.peek();                this.stackMin.push(newMin);            }            this.stackData.push(newNum);        }        public int pop() {            if (this.stackData.isEmpty()) {                throw new RuntimeException("Your stack is empty.");            }            this.stackMin.pop();            return this.stackData.pop();        }        public int getmin() {            if (this.stackMin.isEmpty()) {                throw new RuntimeException("Your stack is empty.");            }            return this.stackMin.peek();        }    }
0 0