问题
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 reversed linked list have the same element.
public static Boolean isPalindrome(Node input){
Node reversed= reverse(input);
while (input!=null){
if(input.item!=reversed.item)
return false;
input=input.next;
reversed=reversed.next;
}
return true;
}
static Node head;
public static Node reverse(Node input){
if(input==null || input.next==null){
head=input;
return input;
}
else{
reverse(input.next);
input.next.next=input;
input.next=null;
return head;
}
}
This program works. But I thought, when execute the reverse method, since the original linked list's head gets passed in, so the original linked list might changed as well, so the isPalindrome should also return true, right ? Am I right or can you tell me if I misunderstood any concept? thanks
This is the main function and how I use that code:
public static void main(String [] args){
Node a=new Node(9);
Node b=new Node(8);
Node c=new Node(7);
Node d=new Node(6);
a.next=b;
b.next=c;
c.next=d;
//d.next=c;
Boolean tf=isPalindrome(a);
if (tf)
System.out.println("Is Palindrome!");
else
System.out.println("Not Palindrome");
}
回答1:
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.
来源:https://stackoverflow.com/questions/30129232/how-to-check-if-a-linked-list-is-a-palindrome-or-not-in-java