How to implement a stack which will support following operations in O(1) time complexity?
1) push() which adds an element to the top of stack.
2) pop() which removes an element from top of stack.
3) findMiddle() which will return middle element of the stack.
4) deleteMiddle() which will delete the middle element.
Push and pop are standard stack operations.
The important question is, whether to use a linked list or array for implementation of stack?
Please note that, we need to find and delete middle element. Deleting an element from middle is not O(1) for array. Also, we may need to move the middle pointer up when we push an element and move down when we pop(). In singly linked list, moving middle pointer in both directions is not possible.
The idea is to use Doubly Linked List (DLL). We can delete middle element in O(1) time by maintaining mid pointer. We can move mid pointer in both directions using previous and next pointers.
Following is C implementation of push(), pop() and findMiddle() operations. Implementation of deleteMiddle() is left as an exercise. If there are even elements in stack, findMiddle() returns the first middle element. For example, if stack contains {1, 2, 3, 4}, then findMiddle() would return 2.
请参考 http://www.geeksforgeeks.org/design-a-stack-with-find-middle-operation/
另外更好的一种解法 参考 http://pastebin.com/3shA8jgx
#include <bits/stdc++.h>
using namespace std;
typedef struct ListNode{
int val;
ListNode *next,*prev;
ListNode(int v){
val=v;
next=prev=NULL;
}
}ListNode;
class Stack {
public:
ListNode *head,*tail,*middle;
int co;
Stack(){
head=tail=middle=NULL;
co=0;
}
void push(int v){
if(head==NULL){
head=new ListNode(v);
tail=head;
}
else{
ListNode* t=new ListNode(v);
t->next=head;
head->prev=t;
head=t;
}
++co;
if(co==1){
middle=head;
}
else{
if(!(co&1)){
middle=middle->prev;
}
}
}
void pop(){
if(co==0){
cout<<"stack is empty\n";
return;
}
ListNode* t=head;
head=head->next;
free(t);
--co;
if(co==0){
head=tail=middle=NULL;
return;
}
if(co==1){
middle=head;
}
else{
if(co&1){
middle=middle->next;
}
}
}
int getmiddle(){
if(co==0){
cout<<"stack is empty\n";
return -1;
}
else{
return middle->val;
}
}
void popmiddle(){
if(co==0){
cout<<"stack is empty\n";
return;
}
--co;
ListNode* t=middle;
if(co==0){
free(t);
head=tail=middle=NULL;
return;
}
if((co&1)){
middle=middle->next;
if(t->prev==NULL){
head=middle;
if(middle)middle->prev=NULL;
free(t);
}
else{
t->prev->next=middle;
if(middle)middle->prev=t->prev;
free(t);
}
}
else{
middle=middle->prev;
middle->next=t->next;
if(t->next!=NULL){
t->next->prev=middle;
}
free(t);
}
}
void print(){
if(head==NULL){
cout<<"stack is empty\n";
return;
}
for(ListNode* t=head;t!=NULL;t=t->next){
cout<<t->val<<" ";
}
cout<<"\n";
}
};
int main(){
Stack s;
while(1){
int op;
cin>>op;
switch(op){
case 0:
int x;
cin>>x;
s.push(x);
break;
case 1:
s.pop();
break;
case 2:
s.print();
break;
case 3:
cout<<s.getmiddle()<<"\n";
break;
case 4:
s.popmiddle();
break;
}
}
return 0;
}