python 输入一个链表,反转链表后,输出新链表的表头

'''
假设链表: None 100 200 300 400 None
链表反转

思路:
两个游标pre和current,curent记录当前节点,pre一个记录当前节点的上一个节点
'''

class Node:
	'''节点类'''
	def __init__(self,value):
		self.value = value
		self.next = None

class Solution:
	def reverse_link_list(self,head):
		'''空链表 或者只有一个节点的链表'''
		if head is None or head.next is None:
			return head
		
		#准备工作:两个指针的初始位置
		curent = head	#指针current指向head
		pre = None	#指针pre指向head的前面的None
		
		#循环向后移动curenet和pre,移动过程中反转链表:current.next = pre
		#循环结束条件为current走到最后指向None,这时pre指向的就是头结点
		while current is not None:
			#记录下没移动前current.next指向的位置,因为待会儿要变动current,current.next也会发生变化
			next_node = current.next
			#1. 当前节点的指针指向前一个节点
			current.next = pre
			#2. 前一个节点向后移动一位
			pre = current
			#3. 当前节点向后移动
			current = next_node
		
		return pre
			
if __name__ == '__main__':
	s = Solution()
	#100->200->300->400
	n1 = Node(100)
	n1.next = Node(200)
	n1.next.next = Node(300)
	n1.next.next.next = Node(400)
	#反转后获取头结点:400
	print(s.reverse_link_list(n1).value)

你可能感兴趣的:(#python,数据结构)