I notice that linkedList has some methods like pop and push. Typically, if I want to use the feature of stack (FILO).Would the linkedList be the best choice?
-
1It depends on your use case. A `LinkedList` could be used as a stack, but it doesn't necessarily mean that it will be the best implementation to fit your needs. – Jeffrey Aug 21 '15 at 16:25
2 Answers
LinkedList
will work, and in fact implements the most stack-like interface in the JDK, Deque
.
ArrayDeque
is the other main non-threadsafe implementation, and is probably more efficient if you only need the stack operations. The above link for Deque
lists the other two JDK-provided implementations, which are thread safe.
There is no better or worse approach to implement a stack but they have different advantages.
Implementation based on linked list gives you more flexibility over the container's capacity since you can theoretically always add more elements to it. Array based stack is more limited in terms of capacity. Linked list implicate more space overhead though, as you need to store references to other nodes.
Performance wise with a stack you only access the top element which means you don't need the random access feature that an array gives you over linked lists.

- 1