Palindrome Linked List
Implement a function to check if a linked list is a palindrome.
Example
Given 1->2->1
, return true
Challenge
Could you do it in O(n) time and O(1) space?
1\find out the medium index of Linked list
2\ reverse the right part of linked list in place
3\compare their value;
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param head a ListNode * @return a boolean */ public boolean isPalindrome(ListNode head) { // Write your code here if(head==null || head.next==null) return true; if(head.next.next==null) { if(head.val==head.next.val) return true; else return false; } ListNode fast=head; ListNode slow=head; while(fast.next!=null && fast.next.next!=null ) { fast=fast.next.next; slow=slow.next; } ListNode head2=slow.next; ListNode pre=null; ListNode cur=head2; slow.next=null; while(cur!=null) { ListNode next=cur.next; cur.next=pre; pre=cur; cur=next; } head2=pre; ListNode p=head; ListNode q=head2; while(q!=null) { if(p.val==q.val) { p=p.next; q=q.next; } else return false; } return true; }