Why and when should I use Stack or Queue data structures instead of Arrays/Lists?

Technology CommunityCategory: Data StructuresWhy and when should I use Stack or Queue data structures instead of Arrays/Lists?
VietMX Staff asked 3 years ago

Because they help manage your data in more a particular way than arrays and lists. It means that when you’re debugging a problem, you won’t have to wonder if someone randomly inserted an element into the middle of your list, messing up some invariants.

Arrays and lists are random access. They are very flexible and also easily corruptible. If you want to manage your data as FIFO or LIFO it’s best to use those, already implemented, collections.

More practically you should:

  • Use a queue when you want to get things out in the order that you put them in (FIFO)
  • Use a stack when you want to get things out in the reverse order than you put them in (LIFO)
  • Use a list when you want to get anything out, regardless of when you put them in (and when you don’t want them to automatically be removed).