|
| 1 | +/** |
| 2 | + * Definition for singly-linked list. |
| 3 | + * function ListNode(val) { |
| 4 | + * this.val = val; |
| 5 | + * this.next = null; |
| 6 | + * } |
| 7 | + */ |
| 8 | +/** |
| 9 | + * Key: find the middle of the list first |
| 10 | + * reverse the second half and then compare it with first half |
| 11 | + *@param {ListNode} head |
| 12 | + *@return {boolean} |
| 13 | + */ |
| 14 | +varisPalindrome=function(head){ |
| 15 | +if(!head||!head.next)returntrue; |
| 16 | +varfastHead=head; |
| 17 | +varslowHead=head; |
| 18 | +while(fastHead.next&&fastHead.next.next){ |
| 19 | +slowHead=slowHead.next; |
| 20 | +fastHead=fastHead.next.next; |
| 21 | +} |
| 22 | + |
| 23 | +// reverse the scond half |
| 24 | +varcenter=slowHead.next; |
| 25 | +varcenterNext=center.next; |
| 26 | +slowHead.next=null; |
| 27 | +center.next=null; |
| 28 | +while(centerNext){ |
| 29 | +vartmp=centerNext.next; |
| 30 | +centerNext.next=center; |
| 31 | +center=centerNext; |
| 32 | +centerNext=tmp; |
| 33 | +} |
| 34 | + |
| 35 | +while(head&¢er){ |
| 36 | +if(head.val!==center.val)returnfalse; |
| 37 | +head=head.next; |
| 38 | +center=center.next; |
| 39 | +} |
| 40 | + |
| 41 | +returntrue; |
| 42 | +}; |