class Node(): def __init__(self,value,next): self.value = value self.next = next class Link(): def __init__(self,head): self.link_create(head) def link_create(self,head): self.head = Node(head,None) self.tail = self.head def link_insert(self,value): temp_node = Node(value,None) self.tail.next = temp_node self.tail = temp_node #通俗的中心思想:断开后继指针,当前节点指向前驱节点 def link_reverse(self): temp_pre = self.head #前驱指针 temp = self.head.next #当前指针 temp_next = temp.next #后继指针 temp_pre.next = None while temp_next != None: #逆指向 temp.next = temp_pre #三个指针分别向后挪一位 temp_pre = temp temp = temp_next temp_next = temp.next
#别忘了连上最后一个节点,将头指针指向最后一个节点 temp.next = temp_pre self.head = temp def link_print(self): temp_node = self.head while temp_node != None: print temp_node.value temp_node = temp_node.next head = Link("1") for i in range(2,8): head.link_insert(i) head.link_print() head.link_reverse() head.link_print()
效果图: