日萌社
人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新)
问题1:输入一个链表,反转链表后,输出新链表的表头。
-
考察点:数据结构中的链表。
class ListNode:
def __init__(self,value):
self.value = value
self.next = None
def ReverseList(pHead):
'''空链表 或者只有一个节点的链表'''
if pHead is None or pHead.next is None:
return pHead
current = pHead # 指针current指向head
pre = None # 指针pre指向head的前面的None
# 循环向后移动curenet和pre,移动过程中反转链表:current.next = pre
# 循环结束条件为current走到最后指向None,这时pre指向的就是头结点
while current is not None:
# 记录下没移动前current.next指向的位置,因为待会儿要变动current,current.next也会发生变化
next_node = current.next
# 1. 当前节点的指针指向前一个节点
current.next = pre
# 2. 前一个节点向后移动一位
pre = current
# 3. 当前节点向后移动
current = next_node
return pre
if __name__ == '__main__':
n1 = ListNode(100)
n1.next = ListNode(200)
n1.next.next = ListNode(300)
n1.next.next.next = ListNode(400)
print(ReverseList(n1).value)
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
-
考察点: python中常用字符串处理方法。
def Permutation(ss):
if len(ss) == 0:
return []
if len(ss) == 1:
return [ss]
res = set()
for i in range(len(ss)):
for j in Permutation(ss[:i] + ss[i + 1:]):
res.add(ss[i] + j)
return sorted(res)
print(Permutation('aabbccd'))