Stacks
– Insert or push some item “x” onto the stack.
* Before this operation, the stack if often checked if it has enough capacity to accommodate the new item
* If stack is full, an overflow would occur
Push (x)
Pop( )
Top( )
IsEmpty( )
IsFull()
Create
– removes all elements from the stack and releases memory allocated to stack
Destroy
Array Implementation
Disadvantage of Array Implementation of Stacks
Linked-List Implementation
Push
Pop
: inserts an element on the front of the list
* insertFront(x)
: returns and removes the element at the front of the list
* removeFront()
: inserts an element on the back of the list
* insertBack(x)
: returns and removes the element at the end of the list
* removeBack()
: inserts an element on the front of the list.
1) Allocate a new node
2) Have new node point to old head
3) Update head to point to new node
insertFront(x)
: returns and removes the element at the front of the list.
1) Update head to point to next node in the list.
2) Return element of previous head and delete the node.
removeFront()
: inserts an element on the back of the list.
1) Allocate a new node
2) If tail is NULL, update head and tail to point to the new node; otherwise.
* Have the old tail point to the new node.
* Update tail to point to new node.
insertBack(x)
: returns and removes the element at the end of the list.
1) No efficient way of doing.
2) Typically would not use a linked-list if this operation is commonly used
removeBack()
Recursion Implementation
O(N) vs O(1)
Advantages & Disadvantages of Stacks
Advantages of Stacks
* Helps manage the data in particular way (LIFO) which is not possible with Linked list and array.
* When function is called the local variables are stored in stack and destroyed once returned. Stack is used when variable is not used outside the function.
* It gives control over how memory is allocated and deallocated.
* Stack frees you from the burden of remembering to cleanup(read delete) the object
* Not easily corrupted (No one can easily inset data in middle)
Disadvantages of Stacks
* Stack memory is limited.
* Creating too many objects on the stack will increase the chances of stack overflow
* Random access not possible