"""
Created on Wed Dec 26 18:48:22 2018
3.从尾到头打印链表
**题目:**输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
**思路:**正向打印,然后翻转
"""
class Listcode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def printListFromTailToHead(self,listNode):
result=[]
p=listNode
while p:
result.append(p.val)
p=p.next
return result[::-1]
if __name__=='__main__':
A1=Listcode(1)
A2=Listcode(2)
A3=Listcode(3)
A4=Listcode(4)
A5=Listcode(5)
A1.next=A2
A2.next=A3
A3.next=A4
A4.next=A5
solution=Solution()
ans=solution.printListFromTailToHead(A1)
print(ans)
#转自:https://blog.csdn.net/XiaoYi_Eric/article/details/81452014
"""
4.重建二叉树
**题目:**输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},
则重建二叉树并返回。
**题解:**首先前序遍历的第一个元素为二叉树的根结点,
那么便能够在中序遍历之中找到根节点,那么在根结点左侧则是左子树,
假设长度为M.在根结点右侧,便是右子树,假设长度为N。
然后在前序遍历根节点后面M长度的便是左子树的前序遍历序列,
再后面的N个长度便是右子树的后序遍历的长度。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre)==0:
return None
if len(pre)==1:
return TreeNode(pre[0])
else:
flag=TreeNode(pre[0])
flag.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
flag.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:])
return flag
if __name__=='__main__':
solution=Solution()
pre=list(map(int,input().split(',')))
tin=list(map(int,input().split(',')))
ans=solution.reConstructBinaryTree(pre,tin)
print(ans.val)
"""
5.用两个栈实现队列
**题目:**用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
**题解:**申请两个栈Stack1和Stack2,Stack1当作输入,
Stack2当作pop。当Stack2空的时候,将Stack1进行反转,并且输入到Stack2。
来源:CSDN
原文:https://blog.csdn.net/XiaoYi_Eric/article/details/81452014
"""
class Solution:
def __init__(self):
self.Stack1=[] #用列表作为栈
self.Stack2=[]
def push(self, node):
# write code here
self.Stack1.append(node)
def pop(self):
# return xx
if self.Stack2==[]:
while self.Stack1:
self.Stack2.append(self.Stack1.pop())
return self.Stack2.pop()
return self.Stack2.pop()
#这时栈2队列的数据出对的顺序,若栈2不空,则可以直接出队
if __name__=='__main__':
solution = Solution()
solution.push(1)
solution.push(2)
solution.push(3)
print(solution.pop())
"""
6.旋转数组的最小数字
**题目:**把一个数组最开始的若干个元素搬到数组的末尾,
我们称之为数组的旋转。输入一个非减排序的数组的一个旋转,
输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,
该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
**题解:**遍历数组寻找数组最小值。
"""
class Solution:
def minNumberInRotateArray(self, rotateArray):
#因为数组为非减的,所以找最小值
if not rotateArray:
return 0
for i in range(1,len(rotateArray)):
if rotateArray[i]<rotateArray[i-1]:
return rotateArray[i]
return 0
if __name__=='__main__':
solution=Solution()
rotateArray=[3,4,5,1,2]
ans=solution.minNumberInRotateArray(rotateArray)
print(ans)