题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
链表题要注意不要用变量的思想去看,要把常规的变量思想转为链表。链表的最后为null值
pre = None 指向cur的前一个
cur = head 指向当前链表头
next = None 指向cur的下一个
判断cur是否为空,若非空则进行遍历,直到cur指向null 此时 pre指向原链表的最后一个值,作为新链表的表头直接返回则得到当前链表的逆转。
# 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 pre = None cur = head while(cur): next = cur.next cur.next = pre pre = cur cur = next return pre