234. Palindrome Linked List 判断链表是否出现回文

234. Palindrome Linked List


Given a singly linked list, determine if it is a palindrome.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool isPalindrome(ListNode* head) {
12         if (!head || !head->next) return true;
13         ListNode *slow = head, *fast = head;
14         while (fast->next && fast->next->next) {
15             slow = slow->next;
16             fast = fast->next->next;
17         }
18         ListNode *last = slow->next, *pre = head;
19         while (last->next) {
20             ListNode *tmp = last->next;
21             last->next = tmp->next;
22             tmp->next = slow->next;
23             slow->next = tmp;
24         }
25         while (slow->next) {
26             slow = slow->next;
27             if (pre->val != slow->val) return false;
28             pre = pre->next;
29         }
30         return true;
31     }
32 };

 

posted @ 2017-10-29 18:05  绿宝宝怪  阅读(129)  评论(0编辑  收藏  举报
#site_nav_under,#ad_under_post_holder,#under_post_news,#google_ad_c2,#under_post_kb{ width:0; height:0; display:none; overflow:hidden; }