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

老子叫甜甜 提交于 2019-12-02 02:26:16

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!