【leetcode】206: 反转链表

题目如下:

本题目可以引入两个变量,一个变量pre,一个变量instant,这两个既是变量,也是指针,我们用head指针不断往后进行移动,每往后移动一次,instant变量就保存当前head的指针,然后instant.next指向pre指针 ,然后将instant的地址赋予pre指针,这样pre就做到了在head向前移动的时候自己反向移动,两相交替,非常神奇。代码如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre=None
        instant=None
        while head:
            instant=head
            head=head.next
            instant.next=pre
            pre=instant
        return pre

速度如下:

也还有更加麻烦的方法,暴力遍历两次,虽然也是O(n),但不够巧妙,这里就不解释啦

原文地址:https://www.cnblogs.com/geeksongs/p/15212656.html