题目描述:
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
思路:将链表前半部分存入vector容器,和后半部分比较,由于不知道链表长度,使用快慢指针来取链表前半部分,注意链表长度为奇数时,跳过中间的元素
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Palindrome {
public:
bool isPalindrome(ListNode* pHead) {
// write code here
ListNode *pFast = pHead;
ListNode *pSlow = pHead;
vector<int> tmp;
//链表长度为偶数
while (pFast != nullptr && pFast->next != nullptr) {
tmp.push_back(pSlow->val);
pSlow = pSlow->next;
pFast = pFast->next->next;
}
//链表长度为奇数
if (pFast != nullptr) {
pSlow = pSlow->next;
}
//比较前半部分和后半部分
int len = tmp.size();
while (pSlow != nullptr) {
if (tmp[--len] != pSlow->val)
return false;
pSlow = pSlow->next;
}
return true;
}
};