题目描述:请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:将链表中的数据转存到数组中,在数组中用双指针比较
/**
* 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) {
if(head==NULL) return true;
if(head->next==NULL)return true;
ListNode* cur = head;
vector<int> number;
int res = cur->val;
while(cur&&cur->next){
number.push_back(cur->val);
cur = cur->next;
}
number.push_back(cur->val);
int count = number.size();
for(int i=0;i<number.size();i++){
if(number[i]!=number[count-1-i]) return false;
if(i>=count-1-i) return true;
}
return true;
}
};