next_node = current_node.get_next() if not next_node: reversed_head = current_node current_node.set_next(pre_node) pre_node = current_node current_node = next_node return reversed_head def reverse_recursively(head_node): if not head_node or not head_node.get_next(): return head_node else: # reversed_head 用来保留递归结束后,想要输出的头节点 reversed_head = reverse_recursively(head_node.get_next()) head_node.get_next().set_next(head_node) head_node.set_next(None) return reversed_head if __name__ == "__main__": my_link = Link() my_link.add(2) my_link.add(3) my_link.add(4) my_link.show() #out_link_head = reverse_iteratively(my_link.head) out_link_head = reverse_recursively(my_link.head) while out_link_head: print out_link_head.data out_link_head = out_link_head.get_next()
if not next_node: reversed_head = current_node current_node.set_next(pre_node) pre_node = current_node current_node = next_node return reversed_head def reverse_recursively(head_node): if not head_node or not head_node.get_next(): return head_node else: # reversed_head 用来保留递归结束后,想要输出的头节点 reversed_head = reverse_recursively(head_node.get_next()) head_node.get_next().set_next(head_node) head_node.set_next(None) return reversed_head if __name__ == "__main__": my_link = Link() my_link.add(2) my_link.add(3) my_link.add(4) my_link.show() #out_link_head = reverse_iteratively(my_link.head) out_link_head = reverse_recursively(my_link.head) while out_link_head: print out_link_head.data out_link_head = out_link_head.get_next()
tmp_stack = Stack() while head_node: tmp_stack.push(head_node.get_data()) head_node = head_node.get_next() print "output:" while not tmp_stack.is_empty(): print tmp_stack.pop() def print_recursively(head_node): if not head_node: return None else: print_recursively(head_node.get_next()) print head_node.get_data() if __name__ == "__main__": my_link = Link() my_link.add(2) my_link.add(3) my_link.add(4) my_link.show() print_iteratively(my_link.head) my_link2 = Link() my_link2.add(5) my_link2.add(6) my_link2.add(7) my_link2.show() print_iteratively(my_link2.head)
if not head_node: return None tmp_stack = Stack() while head_node: tmp_stack.push(head_node.get_data()) head_node = head_node.get_next() print "output:" while not tmp_stack.is_empty(): print tmp_stack.pop() def print_recursively(head_node): if not head_node: return None else: print_recursively(head_node.get_next()) print head_node.get_data() if __name__ == "__main__": my_link = Link() my_link.add(2) my_link.add(3) my_link.add(4) my_link.show() print_iteratively(my_link.head) my_link2 = Link() my_link2.add(5) my_link2.add(6) my_link2.add(7) my_link2.show() print_iteratively(my_link2.head)