-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path92-reverse-linked-list-ii.cs
63 lines (54 loc) · 1.31 KB
/
92-reverse-linked-list-ii.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseBetween(ListNode head, int left, int right)
{
var preLast = FindNthNode(head, left - 1);
var leftNode = FindNthNode(head, left);
var rightNode = FindNthNode(head, right);
var postFirst = FindNthNode(head, right + 1);
Reverse(leftNode, rightNode);
var result = head;
if (preLast == null)
{
result = rightNode;
}
else
{
preLast.next = rightNode;
}
leftNode.next = postFirst;
return result;
}
private ListNode FindNthNode(ListNode head, int n)
{
if (n == 0)
{
return null;
}
if (n == 1)
{
return head;
}
return FindNthNode(head?.next, n - 1);
}
private void Reverse(ListNode left, ListNode right)
{
if (left == right)
{
return;
}
Reverse(left.next, right);
left.next.next = left;
left.next = null;
}
}