27. Leetcode 92. 反转链表 II (链表-反转链表)
生活随笔
收集整理的這篇文章主要介紹了
27. Leetcode 92. 反转链表 II (链表-反转链表)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你單鏈表的頭指針 head 和兩個整數?left 和 right ,其中?left <= right 。請你反轉從位置 left 到位置 right 的鏈表節點,返回 反轉后的鏈表 。示例 1:輸入:head = [1,2,3,4,5], left = 2, right = 4
輸出:[1,4,3,2,5]
示例 2:輸入:head = [5], left = 1, right = 1
輸出:[5]
?
?
?
?
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution:def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:# 初始化 pre, curpre = Nonecur = head# cur 指針到達第m個節點while left > 1:pre = curcur = cur.nextleft -= 1right -= 1# 初始化 con tail con = pretail = cur# 鏈表反轉while right > 0:temp = cur.nextcur.next = prepre = curcur = tempright -= 1if con:con.next = preelse:head = pretail.next = curreturn head總結
以上是生活随笔為你收集整理的27. Leetcode 92. 反转链表 II (链表-反转链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 26. Leetcode 206. 反转
- 下一篇: 28. Leetcode 25. K 个