迭代
# 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: ListNode
:rtype: ListNode
"""
# 空的链表返回空
if not head:
return head
# 链表的尾部节点,记作tail
tail = head
while tail.next:
tail = tail.next
# A记作反转后的第一个节点
A = None
while tail != head:
# p记作头部节点,q记作下一个节点
p = head
q = p.next
# 更新
tail.next = p
head = q
p.next = A
A = p
return head
迭代:优化代码
时间复杂度:O(n)
空间复杂度:O(1)
# 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]:
# Solution 1: 迭代法
# 维护指针p,它的next指向反转链表的头节点
p = ListNode(0)
# 维护指针q,它表示原始链表的当前节点
q = head
# 遍历原始链表,实现q的next指向p的next,同时更新p和q
while q:
k = q.next # 暂存q的next,防止形成环
q.next = p.next # q的next指向p的next,实现反转
p.next = q # 更新p的next
q = k # q往后移动一个节点
# 返回值是p的next
return p.next
递归:
时间复杂度:O(n)
空间复杂度:O(n)
递归的思路不容易理解,可以参考题解https://leetcode.cn/problems/reverse-linked-list/solutions/551596/fan-zhuan-lian-biao-by-leetcode-solution-d1k2/
# 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]:
# Solution 2: 递归
if (head == None or head.next == None) :
return head
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead