题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
Solution 1
//不需要那么复杂,直接转换为字符串,直接判断就可以了
class Palindrome {
public:
bool isPalindrome(ListNode* pHead) {
if(pHead==nullptr||pHead->next==nullptr)
return true;
string str="";
while(pHead!=nullptr)
{
str+=to_string(pHead->val);
pHead=pHead->next;
}
return str==string(str.rbegin(),str.rend());
}
};
Solution 2
//用快慢指针+栈
#include<stack>
class Palindrome {
public:
bool isPalindrome(ListNode* pHead) {
ListNode *fast=pHead,*slow=pHead;
stack<int> stk;
while(fast!=NULL&&fast->next!=NULL)
{
stk.push(slow->val);
slow=slow->next;
fast=fast->next->next;
}
if(fast)//可以用来判断链表长度是奇数还是偶数
slow=slow->next;
while(slow!=NULL)
{
int t=stk.top();
stk.pop();
if(t!=(slow->val))
return false;
slow=slow->next;
};return true;
}
};