Data Structures and Algorithms

On an empty stack, the operations push 1, push 2, pop, push 3, push 4, pop, pop are performed in this order. In what order are the values removed by pop?

  1. A1, 2, 3
  2. B2, 3, 4
  3. C2, 4, 3
Show answer and explanation

Answer: C. 2, 4, 3

A stack is a last-in, first-out (LIFO) structure: the item added last is removed first. After push 1 and push 2, pop removes the top value 2, leaving 1. Pushing 3 and 4 then gives 4, 3, 1 from the top, so the next two pops remove 4 and then 3. The values therefore come out as 2, 4, 3, and 1 remains on the stack. 1, 2, 3 is the order you would get from a queue (first-in, first-out, FIFO), which removes the earliest item first.

  • A. This is the order for a queue (FIFO), which removes items in the order they were added.
  • B. 4 and 3 are reversed. The 4, pushed later, comes out first.
  • C. Correct. The item added last comes out first, giving 2, 4, 3.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. Elements A, B and C are added to an empty queue in this order. Then one element is removed, D is added and one is removed, and E is added and one is removed. In what order are the elements removed?
  2. The expression “3 4 + 2 * 5 −” in reverse Polish notation (postfix notation) is evaluated by pushing each number onto a stack and, for each operator, popping two values, computing the result and pushing it back. What is the result? The left operand of an operator is the value that was pushed earlier.
  3. Which is the correct description of a collision in a hash table?
  4. Keys 10, 17, 24 and 3 are stored in this order in a hash table of size 7 (positions 0 to 6) with the hash function h(k) = k mod 7. Collisions are resolved by linear probing, which moves forward one position at a time (wrapping from 6 to 0) to find a free slot. At which position is key 3 stored?
  5. Which correctly compares chaining (linking the elements at the same position into a linked list) and open addressing (finding another free position within the table) as ways to resolve hash table collisions? The load factor is the number of stored elements divided by the table size.