Given the head
of a singly linked list, return true
if it is a palindrome.
Example 1:
Input: head = [1,2,2,1] Output: true
Example 2:
Input: head = [1,2] Output: false
Solution(Only function):
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode tortoise=head;
ListNode hare=head;
while(hare!=null && hare.next!=null)
{
tortoise=tortoise.next;
hare=hare.next.next;
}
tortoise=reversed(tortoise);
hare=head;
while(tortoise!=null)
{
if(tortoise.val!=hare.val)
return false;
tortoise=tortoise.next;
hare=hare.next;
}
return true;
}
public ListNode reversed(ListNode head)
{
ListNode previous=null;
while(head!=null)
{
ListNode next=head.next;
head.next=previous;
previous=head;
head=next;
}
return previous;
}
}
No comments:
Post a Comment