leetcode第206题,代码是参考别人的
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None:
return
pre = head
cur = head.next
pre.next = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
现在一步步解释代码:
假设原来的链表是这样的:head --> 1 --> 2 --> 3 --> 4 --> 5
pre = head:表示pre现在指向1,pre充当了head的作用
cur = head.next:表示cur现在指向2,因为head是指向1,head.next就是指向2,那么cur=head.next就表示cur指向2
pre.next = None:原来pre是指向1的,现在pre.next就相当于1.next,那这句意思就是pre指向1,1指向None
现在进入while循环,只要cur为真,就是cur只要不是指向None,就一直循环,现在cur指向的是2,前面已经讨论过了
tmp = cur.next:同理可知tmp指向3
cur.next = pre:同理cur指向2,2再指向pre(就是1),相当于cur指向2,2指向1,pre只是一个变量,这句话并不代表cur指向2,2指向 pre,pre指向1
pre = cur:pre现在移动到cur的位置,那就是pre指向2,2指向1,1指向None,pre也是表头,前面有pre = head
cur = tmp:cur移动到tmp的位置
return pre:return pre也就是return head
一个循环下来就是head-->2-->1
整个循环结束后就是head-->5-->4-->3-->2-->1