剑指offer第22题:
输入一个链表,输出链表中倒数第k个节点
剑指offer第24题:
输入一个链表,翻转它
class ListNode:
def __init__(self):
self.value = None
self.next_node = None
class Solution:
def list_generate(self, lst):
"""
传入一个列表将其生成链表
"""
if not lst:
return False
node = ListNode()
node.value = lst[0]
if len(lst) == 1:
node.next_node = None
else:
node.next_node = self.list_generate(lst[1:])
return node
def find_kth_to_tail(self, head_node, k):
"""
寻找倒数第k个节点
"""
if not head_node:
return False
"""
基本思路:
维持两个指针:
一个为目标指针target_node,即指向倒数第k个数。
另外一个为一直向前遍历的指针node,并且用p_head来记录它是第几个节点
当指针node指向最后一个节点,即第n个节点且p_head = n 那么倒数第k个节点为 顺序的第n-k+1节点
所以当p_head==k时,target_node=head_node,当node向前移动时,目标节点也向前移动一位,始终保持着相同距离
当node指向最后一个节点时,则得到target节点
"""
p_head = 0
target_node = None
node = head_node
while node:
p_head += 1
if p_head == k:
target_node = head_node
elif p_head > k:
target_node = target_node.next_node
node = node.next_node
return target_node
def reverse_list(self, head_node):
"""
翻转链表
"""
if not head_node:
return False
p_pre = None
p_next = None
node = head_node
reverse_head_node = None
while node:
if not node.next_node:
reverse_head_node = node
p_next = node.next_node
node.next_node = p_pre
p_pre = node
node = p_next
return reverse_head_node
if __name__ == '__main__':
lst_all = [[],[1],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
for lst in lst_all:
solution = Solution()
head_node = solution.list_generate(lst)
reverse_head_node = solution.reverse_list(head_node)
node = reverse_head_node
while node:
print node.value,
if node.next_node:
print '->',
node = node.next_node
print '\n'