# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if n==m:return head
totalHead=ListNode(0)
totalHead.next=head
left=totalHead
right=totalHead
for i in range(m-1):
left=left.next
tail=left.next
cur1=tail
cur2=tail.next
if cur2==None:return totalHead.next
cur3=tail.next.next
if cur3==None:
cur2.next=cur1
cur1.next=None
left.next=cur2
return totalHead.next
for i in range(n-m):
cur2.next=cur1
cur1=cur2
cur2=cur3
cur3=cur3.next
if cur3==None:
if i==n-m-1:break
cur2.next=cur1
left.next=cur2
tail.next=None
return totalHead.next
left.next=cur1
tail.next=cur2
return totalHead.next
LeetCode-92-Reverse Linked List II 链表反转 各种边界条件
最新推荐文章于 2023-02-04 12:50:18 发布