-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q92_ReverseLinkedList_II.cs
75 lines (66 loc) · 1.84 KB
/
Q92_ReverseLinkedList_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
64
65
66
67
68
69
70
71
72
73
74
75
/**
* 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)
{
if (left == right) return head;
var dummyHead = new ListNode(-501, head);
var current = dummyHead.next;
var direct = dummyHead;
ListNode? reverse = null;
ListNode? rightSideReverse = null;
int count = 0;
while (current != null)
{
count++;
if (count < left)
{
var node = new ListNode(current.val);
direct!.next = node;
direct = direct.next;
}
else if (count >= left && count <= right)
{
var node = new ListNode(current.val, reverse);
if (count == left)
{
rightSideReverse = node;
}
reverse = node;
}
else
{
if (count == right + 1)
{
direct.next = reverse;
}
var node = new ListNode(current.val);
rightSideReverse!.next = node;
rightSideReverse = rightSideReverse.next;
}
current = current.next;
}
if (right == count)
{
if (left == 1)
{
return reverse;
}
else
{
direct.next = reverse;
}
}
return dummyHead.next;
}
}