题目链接:206. 反转链表
我的做法和官方题解略有不同,在此记录一下。
思路
三个指针配合,一个用于保存原有的路径,两个用于反转。
解题过程
设置三个指针 first, second, thrid 分别指向相邻的三个节点。将first和second之间的路径(next指向)反转,然后依次按原路径向前移动这三个指针。当second指针为空的时候,结束循环,first指针即为反转后的头节点。
退化情况处理:当节点个数小于等于1时,返回head。
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)
代码
python3
# 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 head == None or head.next == None:
return head
first = head
second = head.next
first.next = None # 去掉环
while second != None:
third = second.next # 防丢
second.next = first # 反转
first = second # 向前移动
second = third
return first