| | 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.RemoveNodesFromLinkedList; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class RemoveNodesFromLinkedListIterative : IRemoveNodesFromLinkedList |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(1) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public ListNode? RemoveNodes(ListNode? head) |
| 7 | 26 | | { |
| 7 | 27 | | head = Reverse(head); |
| | 28 | |
|
| 7 | 29 | | var dummyHead = new ListNode(); |
| 7 | 30 | | var tail = dummyHead; |
| 7 | 31 | | var maxValue = int.MinValue; |
| | 32 | |
|
| 53 | 33 | | while (head != null) |
| 46 | 34 | | { |
| 46 | 35 | | if (head.val >= maxValue) |
| 25 | 36 | | { |
| 25 | 37 | | maxValue = head.val; |
| 25 | 38 | | tail.next = head; |
| 25 | 39 | | tail = head; |
| 25 | 40 | | } |
| | 41 | |
|
| 46 | 42 | | head = head.next; |
| 46 | 43 | | } |
| | 44 | |
|
| 7 | 45 | | tail.next = null; |
| | 46 | |
|
| 7 | 47 | | return Reverse(dummyHead.next); |
| 7 | 48 | | } |
| | 49 | |
|
| | 50 | | private static ListNode? Reverse(ListNode? head) |
| 14 | 51 | | { |
| 14 | 52 | | ListNode? prev = null; |
| | 53 | |
|
| 14 | 54 | | var curr = head; |
| | 55 | |
|
| 85 | 56 | | while (curr != null) |
| 71 | 57 | | { |
| 71 | 58 | | var next = curr.next; |
| 71 | 59 | | curr.next = prev; |
| 71 | 60 | | prev = curr; |
| 71 | 61 | | curr = next; |
| 71 | 62 | | } |
| | 63 | |
|
| 14 | 64 | | return prev; |
| 14 | 65 | | } |
| | 66 | | } |