| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.ReorderList; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class ReorderListTwoPointers : IReorderList |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | public void ReorderList(ListNode? head) |
| 2 | 25 | | { |
| 2 | 26 | | if (head?.next == null) |
| 0 | 27 | | { |
| 0 | 28 | | return; |
| | 29 | | } |
| | 30 | |
|
| 2 | 31 | | var slow = head; |
| 2 | 32 | | var fast = head; |
| | 33 | |
|
| 5 | 34 | | while (fast.next is { next: not null }) |
| 3 | 35 | | { |
| 3 | 36 | | slow = slow?.next; |
| 3 | 37 | | fast = fast.next.next; |
| 3 | 38 | | } |
| | 39 | |
|
| 2 | 40 | | var stack = new Stack<ListNode>(); |
| | 41 | |
|
| 2 | 42 | | if (slow != null) |
| 2 | 43 | | { |
| 2 | 44 | | var current = slow.next; |
| | 45 | |
|
| 6 | 46 | | while (current != null) |
| 4 | 47 | | { |
| 4 | 48 | | stack.Push(current); |
| | 49 | |
|
| 4 | 50 | | current = current.next; |
| 4 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | slow.next = null; |
| 2 | 54 | | } |
| | 55 | |
|
| 2 | 56 | | var left = head; |
| | 57 | |
|
| 6 | 58 | | while (left != null && stack.Count > 0) |
| 4 | 59 | | { |
| 4 | 60 | | var current = stack.Pop(); |
| | 61 | |
|
| 4 | 62 | | var temp = left.next; |
| | 63 | |
|
| 4 | 64 | | left.next = current; |
| 4 | 65 | | current.next = temp; |
| | 66 | |
|
| 4 | 67 | | left = temp; |
| 4 | 68 | | } |
| 2 | 69 | | } |
| | 70 | | } |