206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
AC代码
使用三指针法而不是改变节点的值
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
prev = None
current = head
while current:
next_node = current.next # 暂存下一节点
current.next = prev # 反转指针
prev = current # 前移prev
current = next_node # 前移current
return prev # 新链表的头节点
总结
三指针法即:
1 → 2 → 3 → 4
1 ← 2 → 3 → 4
1 ← 2 ← 3 → 4
1 ← 2 ← 3 ← 4
即可完成反转