234. Palindrome Linked List

我的方法是:

1.数出链表的长度

2.找到中间的节点,reverse后半截

3.两头开始走比较

 1     public boolean isPalindrome(ListNode head) {
 2         if(head == null || head.next == null) {
 3             return true;
 4         }
 5         int len = 0;
 6         ListNode cur = head;
 7         while(cur != null) {
 8             cur = cur.next;
 9             len++;
10         }
11         ListNode mid = head;
12         for(int i = 0; i < len/2; i++) {
13             mid = mid.next;
14         }
15         mid = reverse(mid);
16         ListNode top = head;
17         int cnt = len / 2;
18         while(cnt > 0) {
19             if(top.val != mid.val) {
20                 return false;
21             }
22             top = top.next;
23             mid = mid.next;
24             cnt--;
25         }
26         return true;
27     }
28     
29     private ListNode reverse(ListNode head) {
30         if(head == null) {
31             return head;
32         }
33         ListNode pre = null;
34         ListNode cur = head;
35         while(cur != null) {
36             ListNode next = cur.next;
37             cur.next = pre;
38             pre = cur;
39             cur = next;
40         }
41         return pre;
42     }

 

posted @ 2016-07-28 23:36  warmland  阅读(120)  评论(0编辑  收藏  举报