请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路:
把值放到数组里,然后双指针比较。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> temp;
while(head)
{
temp.push_back(head->val);
head = head->next;
}
int end = temp.size()-1;
int begin = 0;
while(begin<end)
{
if(temp[begin++]!=temp[end--])
return false;
}
return true;
}
};