回文链表
题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
解题思路
暴力解法,都放到数组里,然后判断数组的回文
代码
/**
* 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> val;
while(head != NULL){
val.push_back(head->val);
head = head->next;
}
int left = 0;
int right = val.size()-1;
while(left < right){
if(val[left] != val[right])
return false;
left++;
right--;
}
return true;
}
};