LeetCode #234 Palindrome Linked List Solution & Explanation

LeetCode Problem

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Follow up: Could you do it in O(n) time and O(1) space?


Solution

In my solution, I used an array to store the values of the linked list, then reversed the array and compared it with the original array.

C# Solution

Solution1

/**
 * 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 bool IsPalindrome(ListNode head) {

        List<int> first = new List<int>();
  
        first.Add(head.val);
        
        while(head.next != null)
        {
            head = head.next;
            first.Add(head.val);
        }
        
        List<int>second = first.ToList();
        first.Reverse();

        return first.SequenceEqual(second);
    }
}

Time Complexity: O(n)

Space Complexity: O(n)

Klook.com

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Palindrome Linked List – LeetCode

Similar Questions

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *