python implements stack structure

stack structure implementation

A stack can be implemented using a sequential list or a linked list.

stack operations

  • Stack() creates a new empty stack
  • push(item) adds a new element item to the top of the stack
  • pop() pops the top element of the stack
  • peek() returns the top element of the stack
  • is_empty() determines whether the stack is empty
  • size() returns the number of elements in the stack
class Stack(object):
    '''Stack, implemented with a sequence list'''
    def __init__(self):
        # In Python, list lists are sequential lists
        self.__list = []

    def push(self, item):
        '''Push stack, add elements'''
        self.__list.append(item)

    def pop(self):
        '''Pop up element'''
        return self.__list.pop()

    def peek(self):
        '''Return the top element of the stack, do not delete the element'''
        if self.is_empty():
            return None
        else:
            return self.__list[-1]

    def is_empty(self):
        '''Determine whether it is empty'''
        return not self.__list

    def length(self):
        '''return the length of the stack'''
        return len(self.__list)



if __name__ == '__main__':
    stack = Stack()

    print(stack.is_empty())
    stack.push(1)
    stack.push(2)
    stack.push(3)
    stack.push(4)
    stack.push(5)

    print(stack.pop())
    print(stack.pop())

    print(stack.peek())
    print(stack.peek())

    print(stack.is_empty())
    print(stack.length())

operation result:

/home/longhui/Desktop/Data Structures and Algorithms/venv/bin/python /home/longhui/Desktop/Data Structures and Algorithms/venv/MyCode/4_stack/my_stack.py
True
5
4
3
3
False
3

Process finished with exit code 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325578118&siteId=291194637