面试题24:反转链表
题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
思路1
从头到尾遍历链表,每到一个新元素时,定义两个指针preNode和nextNode,preNode指向当前元素的上一个元素,nextNode指向当前元素的下一个元素。改变当前元素的指向为preNode,并将preNode和nextNode均向右移动一位。
def ReverseList(self, pHead):
preNode = None
while pHead:
nextNode = pHead.next
pHead.next = preNode
preNode, pHead = pHead, nextNode
return preNode
使用递归实现。不断递归到链表的尾端,更新尾端元素指向其上一个元素,并断开上一个元素的指向。
def ReverseList(self, pHead):
if not pHead or not pHead.next:
return pHead
nextNode = pHead.next
newHead = self.ReverseList(nextNode)
nextNode.next = pHead
pHead.next = None
return newHead
面试题25:合并两个排序的链表
题目:输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
Python(递归调用)
class Solution:
def Merge(self, pHead1, pHead2):
if not pHead1:
return pHead2
if not pHead2:
return pHead1
if pHead1.val <= pHead2.val:
pHead1.next = self.Merge(pHead1.next, pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1, pHead2.next)
return pHead2
def getNewChart(self, list):
if list:
node = ListNode(list.pop(0))
node.next = self.getNewChart(list)
return node
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
if __name__ == '__main__':
list1 = [1, 3, 5]
list2 = [0, 1, 4]
testList1 = Solution().getNewChart(list1)
testList2 = Solution().getNewChart(list2)
final = Solution().Merge(testList1, testList2)
while final:
print(final.val, end=" ")
final = final.next
面试题26:树的子结构
题目:输入两颗二叉树A和B,判断B是不是A的子结构。
class Solution:
# 给定两个二叉树(的根节点)A、B,判断B 是不是A 的二叉树
def HasSubtree(self, pRoot1, pRoot2):
if pRoot1 == None or pRoot2 == None:
return False
result = False
if pRoot1.val == pRoot2.val:
result = self.isSubtree(pRoot1, pRoot2)
if result == False:
result = self.HasSubtree(pRoot1.left, pRoot2) | self.HasSubtree(pRoot1.right, pRoot2)
return result
def isSubtree(self, root1, root2):
if root2 == None:
return True
if root1 == None:
return False
if root1.val == root2.val:
return self.isSubtree(root1.left, root2.left) & self.isSubtree(root1.right, root2.right)
return False