开发者

Single linked list in Python, how to write pop and push?

开发者 https://www.devze.com 2022-12-18 16:17 出处:网络
I am trying to code a class that makes use of Push and Pop from a stack (with single linked list). I am not sure how to write the push and pop functions. I really need a开发者_高级运维 simple example

I am trying to code a class that makes use of Push and Pop from a stack (with single linked list). I am not sure how to write the push and pop functions. I really need a开发者_高级运维 simple example written in Python with the following functions.

Push
Pop
ifEmpty


From the docs that Dyno Fu linked to:

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

And finally, to check if a list is empty:

>>> my_list = []
>>> not my_list
True


And here is the simplest stack class:

class stack(list):
    def push(self,item):
        self.append(item)
    def isEmpty(self):
        return not self

>>> a = stack()
>>> a.push(1)
>> a.isEmpty()
False
>>> a.pop()
1
>>> a.isEmpty()
True
0

精彩评论

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