How wrong is my solution?


  • 0
    F

    I am relatively new to this, I'm just looking for some feedback on how wrong my solution is.
    What I had in mind was check to see if the next node's value equaled the current node's value, to find the middle. Through this process I stored the value of the nodes into a list, of which I use to determine if it's a palindrome on the second half of the linked list.

    Is the idea a potential solution or am I doing it wrong? I provided my (wrong) code below.

    public boolean isPalindrome(ListNode head) {
        if (head == null) return false;
        if (head.next == null) return false;
        while (head.val != head.next.val) {
            list.add(head.val);
            if (head.next == null) return false;
            head = head.next;
        }
        head = head.next.next;
        for (int i = list.size()-1; i > 0; i--) {
            if (list.get(i) != head.val) return false;
            else head = head.next;
        }
        return true;
        
    }

  • 0

    Your middle detection doesn't work. Think of [7,7,1,2,3,4], for example. I don't see a way to detect the middle by looking at the values.


  • 0
    F

    In that case however the for loop at the bottom takes care of that and validates that it isn't going to be a palindrome?


  • 0

    No it doesn't. The list is empty and thus nothing gets checked and thus it returns true.

    And worse, if there is no adjacent duplicate, then your program can crash.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.