How to check if a linked list is a palindrome or not in Java?

后端 未结 1 1611
刺人心
刺人心 2021-01-22 18:35

I wrote a code to check if a singly linked list is a palindrome. And I made two steps:

1st. reverse the original linked list.

2nd. Check if the original and rev

1条回答
  •  無奈伤痛
    2021-01-22 19:08

    Actually, your method is not working. Try it for a list that contains 3,4,5,3. It will return true.

    Also, it changes the list that was passed to it, which is not a very good idea. If you do something like System.out.println(a) (assuming you wrote a proper toString() method) after you run your method, you'll be surprised to find that it only has one item...

    This is indeed because passing an object reference is like passing a pointer in languages like C. If you change the content of that object (and ultimately you do, because in reverse you put null in its next), then it stays changed.

    So why does your program return true? Because input, as I said, becomes a one-item list. reversed contains the full reversed list, and input merely points to its last item. Since you loop on input, then if the first and last items are the same, you'll get true - whether or not the list is a palindrome. That's because you only iterate on the one item that input is pointing to.

    0 讨论(0)
提交回复
热议问题