13. 链表中倒数第k个结点
13.1 题目描述
输入一个链表,输出该链表中倒数第k个结点。
13.2 解题思路
设置两个指针,开始时两个指针均指在头结点,移动前面一个指针,当该指针移动到节点中的第k+1个结点时,表明两个结点之间已经隔了k-1结点,当前面指针移动到尾结点时,则后面指针指向的结点则为倒数第k个结点。
需要注意的是,当所给出的链表为空或者k为0或者所给的k值超过链表的长度时,返回的应该为None。代码如下:
class Solution:
def FindKthToTail(self, head, k):
# write code here
if head is None or k == 0:
return None
index = 0
index_head = head
while head:
if index > k-1:
index_head = index_head.next
head = head.next
index += 1
if k > index:
return None
return index_head
14.反转链表
14.1 题目描述
输入一个链表,反转链表后,输出新链表的表头。
14.2 解题思路
反转链表可以看作将链表中指针的指向全部反转。这样的话,类似于交换两个数字的次序。假设有1,2两个节点,当1的指针不为空时,将1的指针指向1前面的节点,将1添加到反转链表中,再将2设置为1,如此循环下去。为了便于找到2,可在反转1的指针之前对其赋值。注意当输入链表为空或者只有一个值时,返回输入链表即可。代码如下:
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead or not pHead.next:
return pHead
pHead_reverse = None
while pHead:
temp = pHead.next
pHead.next = pHead_reverse
pHead_reverse = pHead
pHead = temp
return pHead_reverse
15.合并两个排序的链表
15.1 题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
15.2 解题思路
新建一个链表,比较所给两个链表的头结点的值,哪个值大,就将其放入新建的链表中,利用递归,直至两个链表中有一个为空。
当所给链表1为空时,返回链表2;链表2为空时,返回链表1。
代码如下:
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 is None:
return pHead2
elif pHead2 is None:
return pHead1
if pHead1.val <= pHead2.val:
pHead = pHead1
pHead.next = self.Merge(pHead1.next, pHead2)
else:
pHead = pHead2
pHead.next = self.Merge(pHead1, pHead2.next)
return pHead
16.树的子结构
16.1 题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
16.2 解题思路
二叉树的问题一般可以用递归解决。
先判断A的根结点与B的根结点是否相同,若根结点相同,再判断A和B的左右子树是否相同;若根结点不同,则要分别判断A的左右子树与B是否相同,直至有一个二叉树为空为止。代码如下:
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
result = False
if pRoot1 is not None and pRoot2 is not None:
if pRoot1.val == pRoot2.val:
result = self.Compare(pRoot1, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.right, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.left, pRoot2)
return result
def Compare(self, Tree1, Tree2):
if Tree2 is None:
return True
if Tree1 is None:
return False
if Tree1.val != Tree2.val:
return False
return self.Compare(Tree1.left, Tree2.left) and self.Compare(Tree1.right, Tree2.right)
17.二叉树的镜像
17.1 题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。源二叉树至镜像二叉树的转变如图所示:
17.2 解题思路
由上图可知源二叉树转变为镜像二叉树只是将二叉树的左右子树调换,用递归方法即可。需要注意的是当左右子树均为空时,停止递归;当左右子树有一个不为空时,执行递归。代码如下:
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
if root is None:
return None
if not root.left and not root.right:
return root
else:
root.left, root.right = root.right, root.left
if root.right:
self.Mirror(root.right)
if root.left:
self.Mirror(root.left)