Explain the implementation of a stack data structure and discuss scenarios where a stack is preferred over a queue.