728x90
LeetCode-92
Reverse Linked List II : Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
note : 1 <= left <= right <= n
Answer
:::python
# 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: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
if not head or left == right:
return head
root = start = ListNode(None)
root.next = head
for _ in range(left-1):
start = start.next
end = start.next
for _ in range(right-left):
tmp, start.next, end.next = start.next, end.next, end.next.next
start.next.next = tmp
return root.next
Result : 34ms Memory: 13.9mb
๋ฐ์ํ
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode-316] Remove Duplicate Letters (0) | 2023.03.30 |
---|---|
[leetcode-20] Valid Parenthese (0) | 2023.03.29 |
[leetcode-24] Swap-Nodes-In-Pairs_2 (0) | 2023.03.21 |
[leetcode 24] Swap Nodes in Pairs (0) | 2023.03.20 |
[leetcode-2] Add Two Numbers (0) | 2023.03.17 |