-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path92-ReverseLinkedList2.cs
47 lines (39 loc) · 1.21 KB
/
92-ReverseLinkedList2.cs
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
37
38
39
40
41
42
43
44
45
46
47
// Problem: https://leetcode.com/problems/reverse-linked-list-ii/
namespace LeetCode {
public partial class Solution {
public ListNode ReverseBetween(ListNode head, int left, int right) {
if(head == null) {
return null;
}
if(left == right) {
return head;
}
ListNode current = head, previous = null;
// find left
while(left > 1) {
previous = current;
current = current.next;
left--;
right--;
}
ListNode lastNodeOfFirstPart = previous;
ListNode lastNodeOfSubList = current;
ListNode next;
while(right > 0) {
next = current.next;
current.next = previous;
previous = current;
current = next;
right--;
}
if(lastNodeOfFirstPart != null) {
lastNodeOfFirstPart.next = previous;
}
else {
head = previous;
}
lastNodeOfSubList.next = current;
return head;
}
}
}