方法1:
将前半段压入栈中,时间O(n),空间O(n);
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<ListNode*> st;
ListNode* cur=head;
int len=0;
while(cur)
{
len++;
cur=cur->next;
}
cur=head;
for(int i=0;i<len/2;i++)
{
st.push(cur);
cur=cur->next;
}
if(len%2!=0)
cur=cur->next;
while(cur)
{
ListNode* top=st.top();
if(top->val==cur->val)
{
cur=cur->next;
st.pop();
}
else
break;
}
if(st.empty())
return true;
return false;
}
};方法2:
将前半段链表逆转
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)
return true;
stack<ListNode*> st;
ListNode* cur=head;
int len=0;
while(cur)
{
len++;
cur=cur->next;
}
cur=head;
ListNode* nx=cur->next;
cur->next=NULL;
for(int i=0;i<len/2-1;i++)
{
ListNode* tail=nx->next;
nx->next=cur;
cur=nx;
nx=tail;
}
ListNode* left=cur;
ListNode* right=nx;
if(len%2==1)
right=right->next;
while(left&&right)
{
if(left->val!=right->val)
return false;
left=left->next;
right=right->next;
}
return true;
}
};
本文介绍两种检测链表是否为回文的有效方法:一种是使用栈存储链表前半部分进行比较;另一种是反转链表前半部分再进行元素值对比。这两种方法均能在O(n)时间内完成检测。
531

被折叠的 条评论
为什么被折叠?



