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  * 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        ListNode *p1 = head;
13         vector<int> vet;
14         if (head == NULL)
15             return true;
16         else
17         {
18             while (p1)
19             {
20                 vet.push_back(p1->val);
21                 p1 = p1->next;
22             }
23         }
24         vector<int> vet1;
25         for (int i = vet.size()-1; i >= 0; --i)
26         {
27             vet1.push_back(vet[i]);
28         }       
29         if (vet1 == vet)
30             return true;
31         else
32             return false;
33     }
34 };

 

posted on 2017-07-06 10:23  无惧风云  阅读(128)  评论(0编辑  收藏  举报