
在遍历的过程中,改变每个节点的 next 指针,让它指向它的前驱节点。
由于单链表没有指向前驱的指针,我们需要在遍历时手动维护一个 prev 变量。
时间复杂度:O(n)O(n)O(n)
空间复杂度:O(1)O(1)O(1)
python
# 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: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
pre = None # 头节点前面的设一个空节点,先不用指向头节点,因为但反过来之后,头节点就指向none
cur = head
while cur:
tmp = cur.next # 暂存后继节点 cur.next
cur.next = pre # 修改 next 引用指向
pre = cur
cur = tmp
return pre