-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution143.cs
49 lines (43 loc) · 1.15 KB
/
Solution143.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
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution143
{
/// <summary>
/// 143. Reorder List - Medium
/// <a href="https://leetcode.com/problems/reorder-list">See the problem</a>
/// </summary>
public void ReorderList(ListNode head)
{
if (head?.next == null)
{
return;
}
// Step 1: Find the middle of the linked list
ListNode slow = head, fast = head;
while (fast is { next: not null })
{
slow = slow.next;
fast = fast.next.next;
}
// Step 2: Reverse the second half
ListNode prev = null, curr = slow, temp;
while (curr != null)
{
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
// Step 3: Merge the two halves
ListNode first = head, second = prev;
while (second?.next != null)
{
temp = first.next;
first.next = second;
first = temp;
temp = second.next;
second.next = first;
second = temp;
}
}
}