Skip to content

Commit 86d7565

Browse files
committed
Leetcode 155. Min Stack
1 parent 8c32c36 commit 86d7565

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

LeetCode/155. Min Stack/Solution.java

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
2+
//push(x) -- Push element x onto stack.
3+
//pop() -- Removes the element on top of the stack.
4+
//top() -- Get the top element.
5+
//getMin() -- Retrieve the minimum element in the stack.
6+
7+
/**
8+
* Your MinStack object will be instantiated and called as such:
9+
* MinStack obj = new MinStack();
10+
* obj.push(x);
11+
* obj.pop();
12+
* int param_3 = obj.top();
13+
* int param_4 = obj.getMin();
14+
*/
15+
16+
class MinStack {
17+
18+
class Node
19+
{
20+
int val;
21+
int min;
22+
Node next;
23+
24+
public Node(int data, int min)
25+
{
26+
this.val = data;
27+
this.min = min;
28+
}
29+
}
30+
Node head;
31+
32+
/** initialize your data structure here. */
33+
public MinStack() {
34+
35+
}
36+
37+
public void push(int x) {
38+
if (head == null)
39+
head = new Node(x, x);
40+
else{
41+
Node newNode = new Node(x, Math.min(x, head.min));
42+
newNode.next = head;
43+
head = newNode;
44+
}
45+
}
46+
47+
public void pop() {
48+
head = head.next;
49+
}
50+
51+
public int top() {
52+
return head.val;
53+
}
54+
55+
public int getMin() {
56+
return head.min;
57+
}
58+
}
59+
60+
/**
61+
* Your MinStack object will be instantiated and called as such:
62+
* MinStack obj = new MinStack();
63+
* obj.push(x);
64+
* obj.pop();
65+
* int param_3 = obj.top();
66+
* int param_4 = obj.getMin();
67+
*/

Stacks and Queues/SortStack.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public static Stack<Integer> sortStack(Stack<Integer> s)
1616
while(!s.isEmpty())
1717
{
1818
int temp = s.pop();
19-
while(!result.isEmpty() && result.peek() > temp)
19+
while(!result.isEmpty() && result.peek() < temp)
2020
{
2121
s.push(result.pop());
2222
}

0 commit comments

Comments
 (0)