给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> s;
if(head==nullptr||head->next==nullptr)
return true;
ListNode* p = head;
while(head!=nullptr)
{
s.push(head->val);
head = head->next;
}
while(!s.empty())
{
int temp = s.top();
s.pop();
if(temp!=p->val)
return false;
p= p->next;
}
return true;
}
};
思路:先用栈实现一遍,简单,但是得遍历两边。
class Solution {
public:
bool isPalindrome(ListNode* head) {
/**
1.找到链表的中间节点
2.原地反转后半部分链表
3.比较前半部分和后半部分链表是否相同
**/
if(head==nullptr) return true;
ListNode* mid = findMid(head);
ListNode* l1=head;
ListNode* l2=mid->next;
l2 = reverseList(l2);
return isSame(l1,l2);
}
ListNode* findMid(ListNode* head)
{
ListNode* fast=head;
ListNode* low=head;
while(fast->next!=nullptr&&fast->next->next!=nullptr)
{
fast=fast->next->next;
low=low->next;
}
return low;
}
ListNode* reverseList(ListNode* head)
{
ListNode* cur= head;
ListNode* pre = nullptr;
while(cur!=nullptr)
{
ListNode* tmp = cur->next;
cur->next= pre;
pre = cur;
cur = tmp;
}
return pre;
}
bool isSame(ListNode* l1,ListNode* l2)
{
ListNode* p1= l1;
ListNode* p2=l2;
while(p2!=nullptr)
{
if(p1->val!=p2->val) return false;
p1=p1->next;
p2=p2->next;
}
return true;
}
};
思路:1.找到链表的中间节点
2.原地反转后半部分链表
3.比较前半部分和后半部分链表是否相同
把链表的找中间和反转两个基本功走一遍