| | 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.PalindromeLinkedList; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class PalindromeLinkedListTwoPointers : IPalindromeLinkedList |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public bool IsPalindrome(ListNode? head) |
| 13 | 26 | | { |
| 13 | 27 | | if (head?.next == null) |
| 1 | 28 | | { |
| 1 | 29 | | return true; |
| | 30 | | } |
| | 31 | |
|
| 12 | 32 | | var values = new List<int>(); |
| | 33 | |
|
| 62 | 34 | | while (head != null) |
| 50 | 35 | | { |
| 50 | 36 | | values.Add(head.val); |
| | 37 | |
|
| 50 | 38 | | head = head.next; |
| 50 | 39 | | } |
| | 40 | |
|
| 12 | 41 | | var left = 0; |
| 12 | 42 | | var right = values.Count - 1; |
| | 43 | |
|
| 28 | 44 | | while (left < right) |
| 20 | 45 | | { |
| 20 | 46 | | if (values[left] != values[right]) |
| 4 | 47 | | { |
| 4 | 48 | | return false; |
| | 49 | | } |
| | 50 | |
|
| 16 | 51 | | left++; |
| 16 | 52 | | right--; |
| 16 | 53 | | } |
| | 54 | |
|
| 8 | 55 | | return true; |
| 13 | 56 | | } |
| | 57 | | } |