📅  最后修改于: 2023-12-03 15:40:01.457000             🧑  作者: Mango
给定一个链表,实现函数reverseBetween
来反转从位置m
到n
的链表。在反转前记录链表的长度,判断链表长度与给定的m
和n
下标是否合法。
例如,
给定单链表1->2->3->4->5
,m = 2
,n = 4
,
返回1->4->3->2->5
。
def reverseBetween(head: ListNode, m: int, n: int) -> ListNode:
pass
head
:链表头指针。m
:待反转链表的起始位置。n
:待反转链表的结束位置。这道题的思路很简单:首先遍历一遍链表,找到待反转链表的起始节点start
和结束节点end
。
设计四个指针:
prev
指向链表m-1
位置的节点,用于连接反转后的链表。cur
指向链表m
位置的节点,用于反转。next
指向链表m+1
位置的节点,用于反转。tail
指向链表n
位置的节点,用于连接后续链表。在反转链表节点时,需要进行以下操作:
while m < n:
next = cur.next
cur.next = prev
prev, cur = cur, next
m += 1
最后,需要连接起前后部分的链表:
start.next = prev
tail.next = cur
完整的实现请参考以下代码:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseBetween(head: ListNode, m: int, n: int) -> ListNode:
if not head or m == n:
return head
cnt, start = 1, ListNode(0, head)
prev, cur = start, head
while cnt < m:
prev, cur = cur, cur.next
cnt += 1
start = prev
while cnt <= n:
next = cur.next
cur.next = prev
prev, cur = cur, next
cnt += 1
start.next.next = cur
start.next = prev
return start.next
# 测试代码
if __name__ == '__main__':
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
m = 2
n = 4
new_head = reverseBetween(head, m, n)
lst = []
while new_head:
lst.append(str(new_head.val))
new_head = new_head.next
assert ''.join(lst) == '14325'