25.复杂链表的复制
**题目:**输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。
**思路:**将大问题转变为小问题,每次都进行复制头部节点,然后进行递归,每次同样处理头部节点。
class RandomList:
def __init__(self,x):
self.val=x
self.next=None
self.random=None
class Solution:
def Clone(self,head):
if not head:
return None
copy=RandomList(head.val)
copy.random=head.random
copy.next=self.Clone(head.next)
return copy
if __name__=='__main__':
A1=RandomList(2)
A2=RandomList(3)
A3=RandomList(4)
A4=RandomList(5)
A5=RandomList(6)
A1.next=A2
A1.random=A3
A2.next=A3
A2.random=A4
A3.next=A4
A3.random=A5
A4.next=A5
A4.random=A3
solution=Solution()
ans=solution.Clone(A1)
ans
56.删除链表中重复的节点
**题目:**在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5。
**思路:**记录链表中出现的数字,然后构建新链表。
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def deleteDuplication(self, head):
dic={}
p=head
while p:
if p.val not in dic:
dic[p.val]=1
else:
dic[p.val]=+1
p=p.next
result=[]
for j in dic:
if dic[j]==1:
result.append(j)
head=ListNode(result[0])
q=head
for i in range(1,len(result)):
node=ListNode(result[i])
q.next=node
q=node
return head
if __name__=='__main__':
pHead1 = ListNode(1)
pHead2 = ListNode(1)
pHead3 = ListNode(2)
pHead4 = ListNode(1)
pHead5 = ListNode(1)
pHead6 = ListNode(1)
pHead7 = ListNode(1)
pHead1.next=pHead2
pHead2.next=pHead3
pHead3.next=pHead4
pHead4.next=pHead5
pHead5.next=pHead6
pHead6.next=pHead7
solution=Solution()
ans=solution.deleteDuplication(pHead1)
print(ans)
58.对称的二叉树
**题目:**请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
**思路:**采用递归的方法来判断两树是否相同。
class TreeNode:
def __init__(self,x):
self.val=x
self.left=None
self.right=None
class Solution:
def isSymmetrical(self, root):
if not root:
return False
return self.same(root.left,root.right)
def same(self,root1,root2):
if not root1 and not root2:
return True
if root1 and not root2:
return False
if not root1 and root2:
return False
if root1.val!= root2.val:
return False
left=self.same(root1.left,root2.right)
if not left:
return False
right=self.same(root1.right,root2.left)
if not right:
return False
return True
if __name__=='__main__':
A1 = TreeNode(1)
A2 = TreeNode(2)
A3 = TreeNode(2)
A4 = TreeNode(3)
A5 = TreeNode(4)
A6 = TreeNode(4)
A7 = TreeNode(3)
A1.left=A2
A1.right=A3
A2.left=A4
A2.right=A5
A3.left=A6
A3.right=A7
solution = Solution()
ans=solution.isSymmetrical(A1)
print(ans)