Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
1、 利用快慢指针找到链表中点
2、从中点开始反转链表,判断是否相等。
1 class Solution { 2 public boolean isPalindrome(ListNode head) { 3 ListNode faster= head ,slower= head; 4 while(faster!=null && faster.next!=null){ 5 faster = faster.next.next; 6 slower = slower.next; 7 } 8 if(faster!=null) 9 //奇数 10 slower=slower.next; 11 ListNode newhead = Reverse(slower); 12 while(newhead!=null){ 13 if(head.val!=newhead.val){ 14 return false; 15 } 16 head = head.next; 17 newhead = newhead.next; 18 } 19 return true; 20 21 } 22 23 public ListNode Reverse(ListNode head) { 24 if(head == null ||head.next == null) return head; 25 ListNode pre = head; 26 head = head.next; 27 pre.next = null; 28 while(head != null){ 29 ListNode next = head.next; 30 head.next = pre; 31 pre = head; 32 head = next; 33 } 34 return pre; 35 } 36 37 }