Implementing a Stack with a Generic Linked List
1 | typedef string Elem; // stack element type |
The principal data member of the class is the generic linked list of type Elem, called S. Since the SLinkedList class does not provide a member function size, we store the current size in a member variable, n.
Code Fragment 5.8: Constructor and size functions for the LinkedStack class.
Our constructor creates the initial stack and initializes n to zero. We do not provide an explicit destructor, relying instead on the SLinkedList destructor to deallocate the linked list S.
1 | LinkedStack::LinkedStack() |
Code Fragment 5.9: definitions of the stack operations, top, push, and pop
Which side of the list, head or tail, should we choose for the top of the stack? Since SLinkedList can insert and delete elements in constant time only at the head, the head is clearly the better choice. Therefore, the member function top returns S.front(). The functions push and pop invoke the functions addFront and removeFront, respectively, and update the number of elements.
1 | // get the top element |
5.1.6: Reversing a Vector using Stack
We can use a stack to reverse the elements in a vector, thereby producing a non-recursive algorithm for the array-reversal problem introduced in Section 3.5.1.
The basic idea is to
- Push all the elements of the vector in order into a stack.
- Then fill the vector back up again by popping the elements off of the stack.
1 | template <typename E> |