Skip to content

Commit 60097a4

Browse files
committed
add min-stack
1 parent 5791b1a commit 60097a4

File tree

4 files changed

+75
-0
lines changed

4 files changed

+75
-0
lines changed

min-stack/MinStack.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Solution.java

min-stack/README.md

Whitespace-only changes.

min-stack/Solution.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class MinStack {
2+
3+
static class Stack {
4+
5+
static class Node {
6+
int val;
7+
Node next;
8+
Node prev;
9+
}
10+
11+
Node head = new Node();
12+
int size = 0;
13+
14+
public void push(int x) {
15+
Node n = new Node();
16+
n.val = x;
17+
n.prev = head;
18+
19+
head.next = n;
20+
head = n;
21+
22+
size++;
23+
}
24+
25+
public void pop() {
26+
head = head.prev;
27+
size--;
28+
}
29+
30+
public int top() {
31+
return head.val;
32+
}
33+
}
34+
35+
Stack data = new Stack();
36+
Stack mins = new Stack();
37+
38+
public void push(int x) {
39+
data.push(x);
40+
41+
if(mins.size == 0 || getMin() >= x){
42+
mins.push(x);
43+
}
44+
}
45+
46+
public void pop() {
47+
int last = data.top();
48+
data.pop();
49+
50+
if(last <= getMin()){
51+
mins.pop();
52+
}
53+
}
54+
55+
public int top() {
56+
return data.top();
57+
}
58+
59+
public int getMin() {
60+
if(mins.size > 0){
61+
return mins.top();
62+
}
63+
64+
throw new IllegalStateException();
65+
}
66+
}

min-stack/index.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
layout: solution
3+
title: Min Stack
4+
date: 2014-11-12 12:19:55+08:00
5+
---
6+
{% assign leetcode_name = {{page.path | remove: '/index.md'}} %}
7+
{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %}
8+
{% include {{leetcode_readme}} %}

0 commit comments

Comments
 (0)