class LNode:
def __init__(self, elem, _next=None):
self.elem = elem
self.next_node = _next
def reverse_list(phead):
if phead == None:
return False
new_head = None
while phead:
if phead.next_node == None:
node = new_head
new_head = phead
new_head.next_node = node
break
tmp_head = phead.next_node
if new_head == None:
new_head = phead
new_head.next_node = None
else:
node = new_head
new_head = phead
new_head.next_node = node
phead = tmp_head
return new_head
def insert_node(phead, elem):
node = LNode(elem)
if phead == None:
phead = node
else:
p = phead
while p.next_node:
p = p.next_node
p.next_node = node
return phead
if __name__ == "__main__":
phead = None
for i in range(10):
phead = insert_node(phead, i)
p = phead
while p:
print(p.elem, end=" ")
p = p.next_node
phead = reverse_list(phead)
p = phead
print("")
while p:
print(p.elem, end=" ")
p = p.next_node
链表反转python实现
最新推荐文章于 2023-12-19 22:18:08 发布