# stack
# In fact, the list in Python can be used as a stack, with Collections.deque can also
# 1. Into the stack list.append (item)
# 2. Out Stack item = List.pop ()
# 3. For the first element out of the stack, you can also item = List.pop (0) and the queue concept
# 4. In fact, you can also take any element out of the Stack item = List.pop (i) is equivalent to deleting element i
# Note that 3,4 is time-consuming.
Stacks can be conveniently used to determine whether a string is a palindrome, but to find the largest palindrome in a long string is the suffix tree.
The following is a stack-based palindrome judgment algorithm
1 #determine if a string is a palindrome (Plalindrome is not Moslems =_=| |)2 #If a string is a palindrome, it must be in the middle symmetry3 #put the first half into the stack, and then the stack to see if you can match the character one by one after mid4 5 defIs_plalindrome_demo1 (A):6MID = Len (A)/2#5/2=2, 4/2=27stack = []8 forIinchRange (mid):9 stack.append (A[i])Ten One ifLen (A)%2 = = 0:#determine whether the length of a string is odd or even ANext = mid#determine the starting subscript for the post-half string - Else: -Next = mid + 1 the -top = Mid-1 - forIinchRange (Next,len (A)): - ifStack[top]! =A[i]: + returnFalse -Top-= 1 + A returnTrue
Test:
if __name__= ="__main__" := List ("Hahahahahahahahaha ") print is_plalindrome_demo1 (q)
Manual implementation Stack
1 #simple filo stack category2 classStack:3 def __init__(self):4Self.top = None#point to top of stack5Self.end = None#Point to the bottom of the stack6Self.count =07 8 defpush (Self,data):9 ifSelf.end = =None:TenSelf.end =Node (data) OneSelf.top =Self.end A Else: -temp = Self.top#Save current stack top -Self.top =Node (data) theSelf.top.next =Temp -Self.count + = 1 - - defpop (self): + ifSelf.top = =None: - Raise "Error:top==none" +data =Self.top.data ASelf.top =Self.top.next atSelf.count-= 1 - returnData
Python data structures and algorithms--stacks