Stacks

Stacks, typically also implemented using linked lists, work differently than queues. Instead of the FIFO ordering, they have a Last In First Out (LIFO) ordering (see Figure 2.9). They have two main operations called push, which adds an item on top of the stack, and pop, which removes and returns one item from the top of the stack. Like queues, stacks are heavily used in many algorithms, such as depth first search traversal, expression evaluations, and many others:

Figure 2.9: Pushing and popping operations on a stack of papers

To model a stack, it's enough to use a simple linked list. The head of the linked list can be used to reference the top of the stack. Every time we need to push something on the top of our stack, we can use the addFront() method we developed in the preceding sections. The implementations differ only in the fact that the pop operation returns the optional item on the top of the stack. Both push and pop can been seen in the Java implementation in the following code snippet. Notice how the pop operations return an optional value which is populated if the stack is not empty.

A one-way linked list is enough to model a stack since we only need to operate from one end of the list. For a queue, we needed to modify both the head and tail of the linked list, hence it was more efficient to use a double linked list. The following code shows the implementation of the push() and pop() methods:

public void push(V item) {
head = new LinkedListNode<V>(item, head);
}
public Optional<V> pop() {
Optional<LinkedListNode<V>> node = Optional.ofNullable(head);
head = node.flatMap(LinkedListNode::getNext).orElse(null);
return node.map(LinkedListNode::getValue);
}
Snippet 2.22: Push and pop operations in java. Source class name: Stack

Go to https://goo.gl/uUhuqg to access the code.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.93.169