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)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值