Palindrome Linked List
Implement a function to check if a linked list is a palindrome.
Example
Given 1->2->1
, return True
Challenge
Could 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 classSolution {/** * @paramhead a ListNode *@returna Boolean*/ Public BooleanIspalindrome (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; }
[Lintcode Medium] Palindrome Linked List