iT邦幫忙

2023 iThome 鐵人賽

DAY 20
0

題目說明

這是 reverse linked list 的進階題

# 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:
    dummy = ListNode(0)
    dummy.next = head
    p = dummy
    for i in range(left - 1):
      p = p.next
    prev = p
    curr = p.next
    tail = curr
    for i in range(right - left + 1):
      next = curr.next
      curr.next = prev
      prev = curr
      curr = next
    p.next = prev
    tail.next = curr
    return dummy.next

上一篇
Day 19 - 141. Linked List Cycle
下一篇
Day 21 - 328. Odd Even Linked List
系列文
Leetcode 習慣養成之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言