方案:
- LIFO : 入栈、出栈
- 递归
- 指向倒序
纯粹是练习,弄着玩的
class Node:
def __init__(self, data, pn=None):
self.data = data
self._next = pn
def __repr__(self):
return str(self.data)
def get_next(self):
return self._next
def set_next(self, pn):
self._next = pn
def reserve_by_stack(node: Node):
'''
利用栈的LIFO特性
'''
stack = [node, ]
n = node.get_next()
while n is not None:
stack.append(n)
n = n.get_next()
while len(stack):
print(stack.pop())
def reserve_by_recursive(node: Node):
'''
递归
'''
if node is not None:
reserve_by_recursive(node.get_next())
print(node)
def reserve_by_reserve(node: Node) -> Node:
'''
修改指向
'''
pre = node
last = pre.get_next()
n = last
pre.set_next(None)
while last is not None:
n = last
last = n.get_next()
n.set_next(pre)
pre = n
return n
def print_node(node: Node):
while node is not None:
print(node)
node = node.get_next()
if __name__ == '__main__':
n3 = Node(3)
n2 = Node(2, n3)
n1 = Node(1, n2)
print("原始顺序:")
print_node(n1)
print("reserve_by_stack:")
reserve_by_stack(n1)
print("reserve_by_recursive:")
reserve_by_recursive(n1)
print("reserve_by_reserve:")
reserved_node = reserve_by_reserve(n1)
print_node(reserved_node)