还有4篇,嗯水!
:- )
1.题目
题目链接:点击这里
2.解决思路
用快慢指针,慢指针一次挪动一个节点,快指针一次挪动两个,这样当快指针停下来时,慢指针就会停在整个链表的中间节点(偶数个结点是中间值偏小的那一个)反转慢指针->next的部分;左半部分链表从头开始看,右半部分链表从尾开始看,逐个结点比较,若全部相同,则为回文链表。
3.代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==nullptr){
return true;
}
ListNode* midptr=middleListNode(head);
ListNode* tailptr=reverseList(midptr->next);
ListNode* checkhead=head;
ListNode* checktail=tailptr;
while(checkhead!=nullptr&&checktail!=nullptr){
if((checkhead->val)!=(checktail->val))
return false;
checkhead=checkhead->next,checktail=checktail->next;
}
return true;
}
ListNode* middleListNode(ListNode* head)
{
ListNode* slow=head;
ListNode* fast=head;
while(fast->next!=nullptr&&fast->next->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
ListNode* reverseList(ListNode* curr)
{
ListNode* prev=nullptr;
while(curr!=nullptr){
ListNode* mid=curr->next;
curr->next=prev;
prev=curr;
curr=mid;
}
return prev;
}
};