Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3292/
>> Solution 1 :Basit linked list, her node'da minimumu tut
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. | |
* Your MinStack object will be instantiated and called as such: | |
* | |
* > MinStack obj = new MinStack(); | |
* > obj.push(x); | |
* > obj.pop(); | |
* > int param_3 = obj.top(); | |
* > int param_4 = obj.getMin(); | |
* | |
*/ | |
class MinStack { | |
private Node top; | |
public MinStack() { | |
top = null; | |
} | |
public void push(int element) { | |
top = new Node (element, top); | |
} | |
public void pop() { | |
Node popped = top; | |
top = top.next; | |
} | |
public int top() { | |
return top.value; | |
} | |
public int getMin() { | |
return top.minValue; | |
} | |
private class Node { | |
int value; | |
int minValue; | |
Node next; | |
Node(int value,Node next){ | |
this.value = value; | |
this.next = next; | |
if(next == null || value < next.minValue){ | |
minValue = value; | |
} else { | |
minValue = next.minValue; | |
} | |
} | |
} | |
} |
Hiç yorum yok:
Yorum Gönder