双指针,从后往前在单向链表中显然不太现实,那么我们就把数据转移到vector连续内存块的序列里!
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
vector<int>s;
int flag = 0;
while (head!=NULL) {
s.push_back(head->val);
head = head->next;
}
int p1 = 0;
int p2 = s.size()-1;
while (p1 <= p2) {
if(s[p1] == s[p2]){
p1++;
p2--;
}
else {
return false;
}
}
return true;
}
};

京公网安备 11010502036488号