Reverse the linked list leetCODE206

Enter a linked list, reverse the list, output the new list header.

Train of thought

Point next of each node to the precursor node pre

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
    def reverseList(self, head):
        """ :type head: ListNode :rtype: ListNode """
        cur, pre = head, None  # Double pointer iteration cur,pre
        while cur: Next points to pre, pre, and cur one place after each iteration
          cur.next, pre, cur = pre, cur, cur.next
        return pre  The pre is the last node
Copy the code