Chuan
Chuan

Reputation: 31

Why LinkedList.removeFirst() = LinkedList.pop()?

I can not understand this.
When we call LinkedList.add(), we add an element to the end of the list, so if we want to mimic a stack with a linked list, we should call LinkedList.removeLast() for pop. I just can not understand why removeFirst() is used for pop?

Upvotes: 3

Views: 4466

Answers (1)

Sysyphus
Sysyphus

Reputation: 1051

Assuming my psychic abilities are correct, and you're using Java:

A list (which implements Deque) can be treated as either FILO (e.g. stack) or FIFO (e.g. queue), with seperate sets of methods for each. In either case, you remove from the front.

When treating it as a stack you use push, to add to the front. When treating it as a queue you use add to add to the end.

Upvotes: 6

Related Questions