采用双指针法,时间复杂度O(n),空间复杂度O(1)
# 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:
pre,cur = None,head #双指针
while cur: #边界条件
temp = cur.next #暂时存储cur.next节点,用于cur指针遍历
cur.next = pre
pre = cur
cur = temp
return pre #返回头部节点
网友评论