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
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.