复杂链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
参考方法二:力扣
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
newNode=dict()
head=pHead
if not pHead:
return None
while pHead:
if pHead in newNode:
new=newNode[pHead]
else:
new=RandomListNode(pHead.label)
newNode[pHead]=new
if pHead.random in newNode:
new.random=newNode[pHead.random]
else:
if pHead.random:
new.random=RandomListNode(pHead.random.label)
newNode[pHead.random]=new.random
if pHead.next in newNode:
new.next=newNode[pHead.next]
else:
if pHead.next:
new.next=RandomListNode(pHead.next.label)
newNode[pHead.next]=new.next
pHead=pHead.next
return newNode[head]
二叉搜索树与双向链表
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
- 首先中序遍历,保存为stack,再次遍历双向连接即可
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
p=pRootOfTree
stack=[]
restack=[]
while p or stack:
if p:
stack.append(p)
p=p.left
else:
node=stack.pop()
restack.append(node)
p=node.right
out=restack[0]
while restack:
top=restack.pop(0)
if restack:
tmp=restack[0]
top.right=tmp
tmp.left=top
return out
字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
- 使用递归即可解决,函数返回当前ss的所有组合
class Solution:
def Permutation(self, ss):
# write code here
tmp=set()
if len(ss) <= 1:
tmp.update(ss)
else:
for i in range(len(ss)):
keep=[ss[i]+j for j in self.Permutation(ss[:i]+ss[i+1:])]
tmp.update(keep)
out=list(tmp)
return sorted(out)