1 public static boolean(ListNode l1,ListNode l2){ 2 boolean res = false; 3 int [] check = {-1}; 4 ListNode mid = getMid(head,check); 5 if( check[0]==1){ 6 ListNode next = mid.next; 7 ListNode newHead =reverse(next); 8 res=checkPalidrom(head, newHead ); 9 newHead =reverse(newHead); 10 mid.next = newHead; 11 } 12 else if(check[0]==0){ 13 ListNode next = mid.next; 14 ListNode newHead =reverse(next); 15 res = checkPalidrom(head, newHead ); 16 newHead =reverse(newHead); 17 mid.next = newHead; 18 } 19 return res; 20 } 21 22 public static ListNode reverse(ListNode head){ 23 if(head==null || head.next==null) return head; 24 ListNode cur = head, post = head.next; 25 while(post!=null){ 26 ListNode temp = post.next; 27 post.next = cur; 28 cur = post; 29 post = temp; 30 } 31 head.next = null; 32 return cur; 33 } 34 35 public static ListNode getMid (ListNode l1, int[] check){ 36 ListNode fast = l1,slow = l1; 37 while(true){ 38 fast = fast.next; 39 if(fast==null) {check[0]=1; return slow; }; 40 fast = fast.next; 41 if(fast==null) { check[0]=0; return slow;}; 42 slow=slow.next; 43 if(slow==fast) return slow; 44 } 45 } 46 public static boolean checkPalidrom(ListNode l1,ListNode l2 ){ 47 while(l1!=null && l2!=null){ 48 if(l1.val!=l2.val) return false; 49 l1 = l1.next; 50 l2 = l2.next; 51 } 52 return true; 53 }
1 find the mid of the list
2check the len is odd or even
3 reverse
4compare
5recover
原文:http://www.cnblogs.com/krunning/p/3568206.html