[LeetCode] Palindrome Linked List

Palindrome Linked List

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?

将链表拆成两半,后一半反转后与前一半一一对比,最后恢复链表。O(n) time and O(1) space!

 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     ListNode *reverseList(ListNode *head) {
12         ListNode *pre = NULL, *cur = head, *tmp;
13         while (cur != NULL) {
14             tmp = cur->next;
15             cur->next = pre;
16             pre = cur;
17             cur = tmp;
18         }
19         return pre;
20     }
21     bool isPalindrome(ListNode* head) {
22         if (head == NULL || head->next == NULL) return true;
23         ListNode *slow = head, *fast = head->next;
24         while (fast != NULL) {
25             fast = fast->next;
26             if (fast != NULL) fast = fast->next;
27             else break;
28             slow = slow->next;
29         }
30         ListNode *head2 = slow->next;
31         slow->next = NULL;
32         head2 = reverseList(head2);
33         ListNode *l1 = head, *l2 = head2;
34         bool res = true;
35         while (l1 != NULL && l2 != NULL) {
36             if (l1->val != l2->val) {
37                 res = false;
38                 break;
39             } else {
40                 l1 = l1->next;
41                 l2 = l2->next;
42             }
43         }
44         head2 = reverseList(head2);
45         slow->next = head2;
46         return res;
47     }
48 };

 

posted @ 2015-07-11 17:12  Eason Liu  阅读(199)  评论(0编辑  收藏  举报