Python algorithm-Stack

Source: Internet
Author: User

Defined:

Stack, aka stacks, is a linear table in which operations are limited. The limitation is that only one end of the table is allowed to insert and delete operations. This end is called the top of the stack, and the opposite end is called the bottom of the stack. Inserting a new element into a stack, also known as a stack, a stack, or a stack, is to put a new element on top of the stack, making it a new stack top element, deleting an element from a stack, or making a stack or fallback, by removing the top element of the stack and making its adjacent elements a new stack top element.

Features: LIFO

Code:

# Encoding=utf-8

Class Node (object):
def __init__ (Self, VAR):
Self.var = var
Self.next = None

Class Stack (object):
def __init__ (self):
Self.top = None
#进栈的逻辑: Top points to the data that just came in, the previous data becomes the top previous data
def push (Self,var):
If var! = None:
Packnode = Node (Var)
Packnode.next = Self.top
Self.top = Packnode
Return Packnode.var
Else
Return None
#出栈的逻辑: Print top of stack element, top pointing to Next
def pop (self):
if self.top = = None:
Return None
Else
TMP = Self.top.var
Self.top = Self.top.next
return tmp

#获取栈顶元素peek ()
def peek (self):
if self.top = = None:
Return None
Else
Return Self.top.var

#写一个实例方法: Gets the value of the bottom element of the stack, and on the basis of the previous question, prints the value of the bottom element, which is usually not
To, just to deepen the understanding of the stack.
Def bottom (self):
if self.top = = None:
Return None
node = Self.top
While Node.next! = None:
node = Node.next
Return Node.var

#进栈1, 4,5,2,3, then 3 nodes out of the stack, using the Peek method to return the value of the top node of the stack
If __name__== ' __main__ ':
s = Stack ()
NodeList = [1,4,5,2,3]
For I in NodeList:
S.push (i)
For I in range (0,len (nodeList)-2):
S.pop ()
Print S.peek ()
Print S.bottom ()

Python algorithm-Stack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.