I am trying to understand Linked Lists. But I am confused with this question. First code works just fine. It reverse the half of the linked list and compare it to the other part. I totally understand it. However, when I reverse the entire list and compare it to the list that was pointed to it at the beginning, it doesn't work.
First code block works.
public bool IsPalindrome(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
// Point fast to original head. Works w/o any problem
fast=head;
slow=Reverse(slow);
while(slow!=null){
if(slow.val!=fast.val)
return false;
slow=slow.next;
fast=fast.next;
}
return true;
}
public ListNode Reverse(ListNode slow){
ListNode prev=null;
while(slow!=null){
ListNode next=slow.next;
slow.next=prev;
prev=slow;
slow=next;
}
return prev;
}
Second code block doesn't work although it does pretty much the same thing. I reverse the entire list and compare it to the list that points to the original ListNode head. I do not modify head but ListNode slow only.
public bool IsPalindrome(ListNode head) {
ListNode first=head;
ListNode second=head;
second=Reverse(second);
while(second!=null && first!=null){
if(second.val!=first.val)
return false;
second=second.next;
first=first.next;
}
return true;
}
public ListNode Reverse(ListNode slow){
ListNode prev=null;
while(slow!=null){
ListNode next=slow.next;
slow.next=prev;
prev=slow;
slow=next;
}
return prev;
}