Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one use Stack<T> instead of List<T>? [closed]

List<T> from System.Collections.Generic does everything Stack<T> does, and more -- they're based on the same underlying data structure. Under what conditions is it correct to choose Stack<T> instead?

like image 342
Billy ONeal Avatar asked Sep 17 '12 20:09

Billy ONeal


People also ask

Why use a stack instead of a list?

You would use stack if you had a need for a Last In First Out collection of items. A list will allow you to access it's items at any index.

Why and when should I use stack data structures instead of arrays lists?

We use stack or queue instead of arrays/lists when we want the elements in a specific order i.e. in the order we put them (queue) or in the reverse order (stack). Queues and stacks are dynamic while arrays are static. So when we require dynamic memory we use queue or stack over arrays.

What is the difference between stack and list in python?

A stack is an abstract data type that serves as a collection of elements with two principal operations which are push and pop. In contrast, a linked list is a linear collection of data elements whose order is not given by their location in memory. Thus, this is the main difference between stack and linked list.

Are stacks and queues more efficient than lists?

Correctly implemented, an array-based stack or queue can be faster and more memory efficient than a linked list implementation.


2 Answers

You would use stack if you had a need for a Last In First Out collection of items. A list will allow you to access it's items at any index. There are a lot of other differences but I would say this is the most fundamental.

Update after your comment:

I would say that using Stack<T> makes a statement about how you want this code to be used. It's always good to plan for the future, but if you have a need for Stack<T> right now, and no compelling reason to use List<T> then I would go with Stack<T>

like image 184
Abe Miessler Avatar answered Sep 22 '22 06:09

Abe Miessler


why I would artificially limit myself to using Stack in new code

There's your answer - you should use Stack when you have a need to enforce a contractual expectation that the data structure being used can only be operated on as a stack. Of course, the times you really want to do that are limited, but it's an important tool when appropriate.

For example, supposed the data being worked with doesn't make any sense unless the stack order is enforced. In those cases, you'd be opening yourself up to trouble if you made the data available as a list. By using a Stack (or a Queue, or any other order-sensitive structure) you can specify in your code exactly how the data is supposed to be used.

like image 45
dimo414 Avatar answered Sep 19 '22 06:09

dimo414