LeetCode-剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路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:
if head is None: return None
l = head
r = head.next
if r is None: # 链表长度为1,直接返回head
return head
temp = r.next
while temp:
if temp: # 如果temp不为空,反转r指针,l,r和temp同时后移
r.next = l
l = r
r = temp
temp = temp.next
else: # 如果temp为空,反转r指针,l指向r
r.next = l
l = r
# 最后temp为空跳出循环,没有修改l,r值
r.next = l
l = r
head.next = None
return l
优化:
# 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 is None: return None
l = head
r = head.next
if r is None:
return head
temp = r.next
while temp:
r.next = l
l = r
if temp:
r = temp
temp = temp.next
r.next = l
l = r
head.next = None
return l
思路2:上面比较好理解,这里其实初始化l指针为空,避免了最后一步head.next = None语句
# 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 is None: return None
l = None
r = head
while r:
temp = r.next
r.next = l
l = r
r = temp
return l
思路3:递归思想
# 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:
def digui(pre, cur):
if cur is None: # 递归找到最后一个结点,cur为None,那么pre就是最后要给结点
return pre
res = digui(cur, cur.next) # 递归最后用res指向尾结点
cur.next = pre # 调整cur指针指向前一个结点pre
return res # 每次返回尾结点
return digui(None, head)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix