- 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.
改用C++
要注意C++ 不用像C一樣 struct Node
還要注意new跟delete
但是這太慢(因為mini每次pop會從找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | struct Node{ int val; struct Node *next; }; class MinStack { public: void push(int x) { cout<<"pust "<<x<<endl; if(stack==NULL){ stack=new Node; stack->val=x; stack->next=NULL; }else{ Node *temp=new Node; temp->val=x; temp->next=stack; stack=temp; } mini = x>mini? mini:x; } void pop() { if(stack!=NULL){ Node *temp; if(stack->val == mini){ temp=stack->next; mini=INT_MAX; while(temp!=NULL){ mini = temp->val >mini? mini:temp->val; temp=temp->next; } } temp=stack->next; delete stack; stack=temp; } } int top() { if(stack!=NULL){ return stack->val; }else return -1; } int getMin() { return mini; } private: Node *stack=NULL; int mini=INT_MAX; }; |
-----------
用兩個stack實作
因為min stack 只會在當下push如果比較小才會放進來
之後不管main怎麼pop 只要不是跟mini的top一樣都沒差
因為main pop != min.top代表 之前都太大 POP也無所謂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // Space efficient class MinStack { private: stack<int> mainStack; stack<int> minStack; public: void push(int x) { mainStack.push(x); // if x == currentMin, also push x to minStack // because when popping, x == currentMin will be // popped if (minStack.empty() || minStack.top() >= x) { minStack.push(x); } } void pop() { int x = mainStack.top(); mainStack.pop(); if (x == minStack.top()) { minStack.pop(); } } int top() { return mainStack.top(); } int getMin() { return minStack.top(); } }; |
--------------
都不用stack的方式
在裡面加入一個nextmini
在另外一個指標去指mini
就是把stack改成pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | struct Node{ int val; struct Node *next; Node *nextmini; }; class MinStack { public: void push(int x) { cout<<"pust "<<x<<endl; if(stack==NULL){ stack=new Node; stack->val=x; stack->next=NULL; stack->nextmini=NULL; mini=stack; }else{ Node *temp=new Node; temp->val=x; temp->next=stack; stack=temp; if(stack->val <= mini->val){ stack->nextmini = mini; mini=stack; } } } void pop() { if(stack!=NULL){ Node *temp; if(stack->val == mini->val){ mini=stack->nextmini; } temp=stack->next; delete stack; stack=temp; } } int top() { if(stack!=NULL){ return stack->val; }else return -1; } int getMin() { return mini->val; } private: Node *stack=NULL; Node *mini=NULL; }; |
沒有留言:
張貼留言