[Java] Leetcode 92. Reverse Linked List II [LinkedList Reversal #2]

preview_player
Показать описание
In this video, I'm going to show you how to solve Leetcode 92. Reverse Linked List II which is related to LinkedList Reversal.

Here’s a quick rundown of what you’re about to learn:

⭐️ Course Contents ⭐️
⌨️ (0:00) Question
⌨️ (2:02) Solution Explain
⌨️ (8:28) Code

In the end, you’ll have a really good understanding on how to solve Leetcode 92. Reverse Linked List II and questions that are similar to LinkedList Reversal.

Now, if you want to get good at LinkedList Reversal, please checkout my LinkedList Reversal playlist.

Рекомендации по теме
Комментарии
Автор

Could you code in the first method? cause this became confusing in the end.

rajaditya
Автор

the code gives Wrong Answer, while submission on Leetcode for the Input --> List Node = [3, 4] left = 1, right = 2

rajaditya
Автор

Solution for first method:

class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
# base case
if head is None: return None

# define current and count
current = head
prevLeftNode = None
afterRightNode = None
leftNode = None
count = 1

# iterate through linked list
while current is not None:
if count == left - 1:
prevLeftNode = current
if count == left:
leftNode = current
if count == right + 1:
afterRightNode = current

count += 1
current = current.next

reversedLL = self.reverse(leftNode, afterRightNode)

if prevLeftNode:
prevLeftNode.next = reversedLL
else:
head = reversedLL

if afterRightNode:
leftNode.next = afterRightNode

if not prevLeftNode and not afterRightNode:
return reversedLL

return head

def reverse(self, left, right):
# define prev and current
current = left
prev = None

# iterate through linked list
while current != right:
temp = current.next
current.next = prev
prev = current
current = temp

return prev

JackMa-