This article example describes the basic definition and use of python stack. Shared for your reference, as follows:
# -*- coding:utf-8 -*- #! python3 # In the design of a wharf, we need to define an instance of the attribute top. three instance methods: fetch the top element of the stack peek(); out pop(); in push() The effect of #stacks: first in, last out class Node(object): ## node, including two attributes, a value for the node and the next pointing for the node def __init__(self,value): = value # Assign a value to a node = None # node's next pointing to class stack(object): def __init__(self): = None # Create a stack, give top the top-of-stack attribute, and top is initially empty. def peek(self): # Get the element at the top of the stack and return the corresponding value. if != None: # If the top of the stack is not empty, that is, there is data on the stack return # Then just return to the top of the stack else: return None # If there is no data on the stack, return None def push(self,node): # Add elements to the stack (arguments include self and node's value, node) if node != None: # If the node, which is joined, is not empty packNode = Node(node) # Instantiate the Node class = # Assign the pointing of the added node to the top of the stack = packNode # Assign the node at the top of the stack to the added node return # Return the value of the node else: return None # Returns None def pop(self): # Out of the stack if == None: # If the stack is empty return None # Returns None else: tmp = # Pass the top-of-stack value to tmp = # Change the stack top pointing to the next node on the current stack top return tmp # Returns the value of the node that went out of the stack s = stack() a = Node(1) print((a).value) print((2)) print((3)) print(()) print((4)) print(()) print(()) print(()) print(().value)
Run results:
1
2
3
3
4
4
3
2
1
Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Summary of Python encryption and decryption algorithms and techniques》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.