题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
链表反转,相关的数据结构的题目,应该马上就想到,定义一个虚拟的节点进行临时数据的存储
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def ReverseList(self , head: ListNode) -> ListNode:
# write code here
var_head = head
if var_head==None or var_head.next==None:
return var_head
present = None # 定义哟个虚拟节点
while var_head:
var_nest = var_head.next # 当前的节点的下一个节点需要变化
# 进行反转操作
var_head.next = present
present = var_head
var_head=var_nest
return present
python语法堂,直接定义一个空的位置,然后依次将相关的位置进行转化赋值
def ReverseList(self , head: ListNode) -> ListNode:
if not head: # 如果非空
return head
a, a.next, b =head, None, head.next # 初始化
while b:
b, a, a.next = b.next, b, a # 遍历
return a