简体   繁体   中英

What is the time complexity of accessing an element in a Stack? Or is it even possible to do it?

One of the tutorials I've watched said that accessing a stack implemented in either a linked list or array takes O(1) time complexity but he also said that 'searching' in unsorted data is not applicable. Now I'm confused if 'searching' is the same with 'accessing'?

One of the tutorials I've watched said that accessing a stack implemented in either a linked list or array takes O(1) time complexity

The tutorial is correct about array-based stacks. Assuming that the stack API permits it, you can get the N from top or N from bottom element of an array-based stack in O(1). It is just an array lookup.

For linked-list based stacks, it is more complicated. You can get the top (or maybe bottom) element in O(1). But getting the N'th from top element is an O(N) operation. You have to follow N references to get to the element you need.

but he also said that 'searching' in unsorted data is not applicable. Now I'm confused if 'searching' is the same with 'accessing'?

They are different things. Consider this:

String[] array = new String[] {"A", "B", "C"};

Accessing an element of array is array[i] . For an array that is an O(1) operation. (For a linked list, the equivalent is O(N) )

Searching for an element of an array is like this:

for (String s : array) {
   if (s.equals("Fred")) {
       // found it!
   }
}

As I have used these words, "accessing" and "searching" clearly mean different things.

Now as Erwin states, the meanings of terms like "searching" and "accessing" will vary from one author to another. But "searching" has a clear implication of needing to look for something ... rather than knowing where it will be.


It is not entirely clear what the tutorial you are reading might mean by "'searching' in unsorted data is not applicable" . It is certainly possible to search in non-sorted data, but that will be an O(N) operation ... unless you have done something to organize the data beforehand. (Se my example code above.)

But then again a stack data structure is typically optimized for the special case of accessing the top of the stack. Not accessing the N'th element, or searching for an element with a particular value.

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