Post

用链表实现队列/栈

只需调用双链表的API即可 Python链表实现栈:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from collections import deque

class MyLinkedStack:
    def __init__(self):
        self.stack = deque()

    def push(self, val):
        self.stack.append(val)

    def pop(self):
        self.stack.pop()

    def getLast(self):
        return self.stack[-1]

    def getSize(self):
        return len(self.stack)

if __name__ == "__main__":
    stack = MyLinkedStack()
    stack.push(1)
    stack.push(2)
    stack.push(3)
    print(stack.pop())
    print(stack.getLast())
    print(stack.getSize())

Python链表实现队列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from collections import deque

class MyLinkedStack:
    def __init__(self):
        self.stack = deque()

    def push(self, val):
        self.stack.append(val)

    def pop(self):
        self.stack.popleft()

    def getLast(self):
        return self.stack[0]

    def getSize(self):
        return len(self.stack)

if __name__ == "__main__":
    stack = MyLinkedStack()
    stack.push(1)
    stack.push(2)
    stack.push(3)
    print(stack.pop())
    print(stack.getLast())
    print(stack.getSize())
This post is licensed under CC BY 4.0 by the author.