简体   繁体   中英

Palindrome Linkedlist using recursion

Indexing starts from 0. Input format: Linked list elements (separated by space and terminated by -1)

There is some runtime error on one hidden test case. main() is taking input and passing head .

public class Solution {
    static String s1="",s2="";
    public static boolean isPalindrome_2(LinkedListNode<Integer> head) {
        if (head != null) {
            s1 = s1 + head.data;
            isPalindrome_2(head.next);
            s2 = s2 + head.data;
        }
        if (s1.equals(s2))
            return true;
        return false;
    }
}

How the algorithm is supposed to work: s1 will store the string containing all data. s2 will store data in reverse manner since it is after recursive function. Then the strings can be compared.

Since you have not provided a reproducible example, I have not been able to run your code and verify any hypotheses. So this is from inspection alone.

  1. If the numbers in the list ar 1 and 11, it is not a palindrome. Yet your string s1 and s2 should both become 111 , that is equal, so your method should return true .
  2. You are not testing for the -1 at the end. Shouldn't you?

BTW I don't see any indexing and I don't see any space between elements.

I also have not understood how a runtime error can occur, sorry. Again, running your code might have given me a greater chance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM