Stack Basics
excerpt: This covers the push, pop and using stacks to reverse an array. tags: sentinel linked-list-traversal
A stack is a data structure where objects are added and removed in last-in-first-out order. They are sometimes called LIFOs. They expand as needed to hold more items just like linked lists. It is often used to store objects for later processing by other algorithms such as shortest-path network algorithms.
It is similar to a pile of books or plates, we cannot remove the item in the middle without making them collapse. The push operation adds an object to a stack. The pop operation removes an object from a stack.
Push Operation
The stack can be implemented using a linked list. The push method adds a new node to the top of the list.
|
|
The code for testing the implementation of the push method consists of the following classes. The node.rb:
|
|
The linked_list.rb:
|
|
The tester.rb:
|
|
Pop Operation
The pop method removes the top node from the list.
|
|
The tester.rb can test the implementation:
|
|
The push and pop operations both have O(1) run times. The list does not require any extra space aside from the links between the nodes. So the linked lists are also space-efficient.
Array Stacks
A stack can also be implemented using an Array. The space for the array must be allocated to hold the number of items we expect to put in the stack. The constructor initializes the size of the array. The array_stack.rb is implemented as shown below:
|
|
The push method implementation can be tested by:
|
|
The pop method can be implemented as shown below:
|
|
The pop method can be tested by:
|
|
The array based stack has O(1) time complexity for adding and removing an item. The array based stack does not need any memory for storing links between nodes. However, it requires extra space to hold new items. If the array needs to be resized for holding more items than the initial allocation of array size, it will take O(N) time to copy the new items into a newly resized array.
Reversing an Array
The shortest path algorithms can use stacks. The reversing of an array is simple with a stack. First push every item onto the stack and then pop every item from the stack. The LIFO nature of the stack reverses the order of the items.
A stack makes it simple to reverse an array. Push each item onto the stack and pop it back off. The LIFO nature of the stack takes the item out in reverse order.
|
|
The loop traverses the values array and saves all the elements in a stack. The pop operation removes all the elements from the array and saves it in the reverse array.
Display Linked List Backwards
Stack is useful to display a linked list backwards. The forward traversal of linked list saves all the nodes in the stack. The stack is then used to access the nodes and prints its value.
|
|