Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
思路:用单链表来实现整个栈,数据结构设置如下
class Node{
int val;
int min;
Node next;
}
int val;
int min;
Node next;
}
对应push操作,如果此时单链表为空
node.min=x;
head=node;
如果单链表不为空,
将x与head.min的较小值赋给node.min
然后node,next=head,head=node;
对于pop操作
head=head.next就行
对于top操作
return head.val
对于getMin操作
return head.min就行
代码如下(已通过leetcode)
class MinStack {
Node head;
class Node{
int val;
int min;
Node next;
}
public void push(int x) {
Node node=new Node();
node.val=x;
if(head==null){
node.min=x;
head=node;
} else{
if(head.min<x){
node.min=head.min;
}else{
node.min=x;
}
node.next=head;
head=node;
}
}
public void pop() {
if(head.next==null){
head=null;
}else{
head=head.next;
}
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
}