简体   繁体   中英

What is worst case time complexity to get the FIRST element placed on a Stack (linked-list)?

Is it Linear Time or Constant Time and why? Is it linear because the first element is on the bottom? Or is it constant because of traversal in linked list?

Confused and seeking explanation. Using Java

Java's LinkedList is a doubly ended queue that maintains a pointer to the first and last element. Anytime you try to get the last element of the LinkedList , it can be directly accessed as it already has a pointer to it. So for getting the last element the time complexity is O(1).

It also has a method getLast() to retrieve the last element.

Your question is ambiguous:

  • The java.util.Stack class not a linked list. It is actually a subtype of Vector and uses an array internally rather than a linked list.

  • In general terms, a "stack" is an abstraction: an API. We can't make definite statements about the complexity of a "stack" without tying them to a specific implementation.

  • Even saying "a stack implemented as a linked list" is not sufficient because you could use a linked list to implement a stack in many ways. There is an obvious way to do it... and there are other ways with varying performance characteristics.

It is also unclear what you mean by "first" and "bottom". I think I have figured it out, but if you are asking questions that need a precise answer, the questions themselves should be precise!

So... lets make some assumptions:

  1. Assume that the "bottom" element is the one that will be popped last if you pop all of the elements of a stack.

  2. Assume that the stack is not java.util.Stack but a reasonable implementation using linked lists; ie push() is implemented as adding a new node to the start of the list, and pop() is implemented as removing the node at the start of the list.

The complexity of push() and pop() will be O(1) .

So what is the complexity of retrieving the "bottom" element of the stack?

Well, if you follow the linked list chain of a stack with N elements, you have N links to traverse to get to the list node for the "bottom" element; ie O(N) .

But if your stack implementation also keeps a pointer to the last list node, you can get the "bottom" list node in O(1) . (Would you do that? Well it depends if you are going to need to get the bottom element frequently!)

Note that the above analysis applies for both singly and doubly linked lists.


Note that if we were talking about an array based stack, the code for getting the bottom element would be roughly equivalent to:

get_bottom() {
    return this.array[this.bottom] 
}

That is O(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM