直接在原有的链表上判断不易,单向链表只能指向下一个方向,因此,可以将链表数值存放在vector中,然后使用双指针识别判断
/**

  • struct ListNode {
  • int val;
  • struct ListNode *next;
  • };
  • /

class Solution {
public:
/*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode
head) {
// write code here
vector<int> temp;
while(head)
{
temp.push_back(head->val);
head=head->next;
}
int len=temp.size(), l=0,r=len-1;
while(l<r)
{
if(temp[l]!=temp[r])
{
return false;
}
l++;
r--;
}
return true;
}
};</int>