简体   繁体   English

表示堆栈的单链接列表

[英]Singly-linked list representing stack

为什么仅当节点之间的链接指向顶部(较新)到底部(较旧)的方向时,为什么我们不能使用单链列表来表示堆栈?

Because otherwise operations like pop() will take O(n) instead of O(1) and same with the other ones. 因为否则pop()类的操作将采用O(n)而不是O(1)并与其他操作相同。 To represent a stack means accessing the last inserted item is the easiest (less time). 表示堆栈意味着最容易(更少的时间)访问最后插入的项目。

Okay i get it now, removing the head of a singly linked list take O(1) time and removing the tail takes O(n) time since you have to do a linear search to find the node that points to the tail and make that node point to null. 好吧,我现在明白了,删除单链列表的头部要花O(1)时间,而删除尾部要花O(n)时间,因为您必须进行线性搜索以找到指向尾部的节点并使之节点指向null。 So if the stack was tail to head (each pointer points up towards top of stack) it would take O(n) every time you popped as opposed to O(1) for a stack thats implemented head to tail (each pointer points to bottom of stack). 因此,如果堆栈是尾对头的(每个指针指向堆栈的顶部),那么每次弹出时都需要O(n),而不是O(1)才能实现从头到尾的堆栈(每个指针都指向底部)的堆栈)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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