题目描述:
方法一:
class Solution:def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:dummy = ListNode(0)dummy.next = headpre = dummyfor i in range(m-1):pre = pre.nextstart = pre.nexttrail = start.nextfor i in range(n-m):start.next = trail.nexttrail.next = pre.nextpre.next = trailtrail = start.nextreturn dummy.next
方法二:
找到要翻转部分的链表,将其翻转,再与原链表拼接;
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:dummy = ListNode(0)dummy.next = headpre = dummyfor i in range(m-1):pre = pre.nextnode =Nonecur = pre.nextfor i in range(n-m+1):tmp = cur.nextcur.next = nodenode = curcur = tmppre.next.next = curpre.next = nodereturn dummy.next