开发者

Where should the top of stack be in linked list implementation of stack?

Here is what a linked list implementing a stack with 3 elements might look like:

list
 |
 v
--------   --------   ---------
| C | -+-开发者_如何学C->| B | -+-->| A | 0 |
--------   --------   ---------

Where should we consider the top of the stack to be, the beginning or end of the list, and why?

Thanks in advance.


The fastest element to access in a linked list is usually the head (some implementations also keep a reference to the tail element though). Since the stack only ever needs to access the top element, that should be the head element of the linked list. This will avoid having to iterate over the entire list for every operation.


list.head will be top of the stack. Elements will be add in head like

Insert(L,x)

1. x.next = head.next
2. head = x

Similarly deletion will be performed in head.

Delete(L)

1. x=head
2. head = head.next 
3. Free x

In this way insertion and deletion will be in performed in LIFO order which is Stack.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜