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.
[ad type=”banner”]
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.
C Programming:
#include <stdio.h>
#include <stdlib.h>
struct DLLNode
{
struct DLLNode *prev;
int data;
struct DLLNode *next;
};
struct myStack
{
struct DLLNode *head;
struct DLLNode *mid;
int count;
};
struct myStack *createMyStack()
{
struct myStack *ms =
(struct myStack*) malloc(sizeof(struct myStack));
ms->count = 0;
return ms;
};
void push(struct myStack *ms, int new_data)
{
struct DLLNode* new_DLLNode =
(struct DLLNode*) malloc(sizeof(struct DLLNode));
new_DLLNode->data = new_data;
new_DLLNode->prev = NULL;
new_DLLNode->next = ms->head;
ms->count += 1;
if (ms->count == 1)
{
ms->mid = new_DLLNode;
}
else
{
ms->head->prev = new_DLLNode;
if (ms->count & 1)
ms->mid = ms->mid->prev;
}
ms->head = new_DLLNode;
}
int pop(struct myStack *ms)
{
if (ms->count == 0)
{
printf("Stack is empty\n");
return -1;
}
struct DLLNode *head = ms->head;
int item = head->data;
ms->head = head->next;
if (ms->head != NULL)
ms->head->prev = NULL;
ms->count -= 1;
if (!((ms->count) & 1 ))
ms->mid = ms->mid->next;
free(head);
return item;
}
int findMiddle(struct myStack *ms)
{
if (ms->count == 0)
{
printf("Stack is empty now\n");
return -1;
}
return ms->mid->data;
}
int main()
{
struct myStack *ms = createMyStack();
push(ms, 11);
push(ms, 22);
push(ms, 33);
push(ms, 44);
push(ms, 55);
push(ms, 66);
push(ms, 77);
printf("Item popped is %d\n", pop(ms));
printf("Item popped is %d\n", pop(ms));
printf("Middle Element is %d\n", findMiddle(ms));
return 0;
}
[ad type=”banner”]
Output:
Item popped is 77
Item popped is 66
Middle Element is 33