-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode 92 -- Reverse Linked List II.py
More file actions
36 lines (31 loc) · 1 KB
/
Leetcode 92 -- Reverse Linked List II.py
File metadata and controls
36 lines (31 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Leetcode 92: Reverse Linked List II
# https://leetcode.com/problems/reverse-linked-list-ii/
# 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]:
dummy = ListNode(0, head)
prev = dummy
for i in range(left - 1):
prev = prev.next
curr = prev.next
# want to reverse 2-4
# 1 -> 2 -> 3 -> 4 -> 5
# prev = 1
# curr = 2
# walk thru one switch in the loop
# dummy node temp set to 3
# 2 -> 4
# 4 -> 2
# prev -> 3
for i in range(right - left):
temp = curr.next # temp = 3
curr.next = temp.next # curr -> 4
temp.next = prev.next # temp -> 2
prev.next = temp # pre -> 3
return dummy.next
#time complexity: O(N)
#space complexity: O(1)