[Leet Code] Palindrome Linked List C#

April 29th, 2020

Time: 100ms Space: 28.7mb You can find the actual problem here.

Thought Process

Since this is a singly linked (each node only contains a reference to the next node and not the previous) linked-list we are going to have to use another data structure to hold the values of the nodes. In this cause I am using a list since I can easily call .Reverse() on it. Finally I am comparing the elements in the original list to the elements in the reversed list, if they are the same then we have a palindrome.

public bool IsPalindrome(ListNode head) {

        List<int> orig = new List<int>();

        if(head == null){
            return true;
        }

        if(head.next == null)
        {
            return true;
        }

        while(head != null)
        {
            orig.Add(head.val);

            if(head.next != null){
                head = head.next;
            } else {
                //end
                head = null;
            }
        }

        List<int> reverse = new List<int>(orig);    
        reverse.Reverse();

        if(reverse.SequenceEqual(orig)){
            return true;
        } else {
            return false;
        }
    }