設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) -- 將元素 x 推入棧中。
pop() -- 刪除棧頂的元素。
top() -- 獲取棧頂元素。
getMin() -- 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/min-stack
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
public class MinStack
{
public int Length;
private readonly LinkedList<int> _1st;
private readonly LinkedList<int> temp;
public MinStack()
{
Length = 0;
_1st = new LinkedList<int>();
temp = new LinkedList<int>();
}
public void Push(int x)
{
Length++;
_1st.AddFirst(x);
if (temp.Count==0||temp.First.Value>=x)
temp.AddFirst(x);
}
public void Pop()
{
if (temp.First.Value == _1st.First.Value)
temp.RemoveFirst();
_1st.RemoveFirst();
Length--;
}
public int Top()
{
return _1st.First.Value;
}
public int GetMin()
{
return temp.First.Value;
}
}
關鍵:在常數時間內找到最小元素。在題目中無法從棧的定義寫起。
如果在其定義一個MinStack,會在構造函數內形成一個死循環,產生錯誤。