class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==nullptr){
return true;
}
ListNode* midNode = halfList(head);
ListNode* endNote = reverseList(midNode);
while(head!=nullptr){
if(head->val!=endNote->val){
return false;
}
head = head->next;
endNote = endNote->next;
}
return true;
}
ListNode* halfList(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* head){
ListNode* currNode = head;
ListNode* preNode = nullptr;
while(currNode!=nullptr){
ListNode* temp = currNode->next;
currNode->next = preNode;
preNode = currNode;
currNode = temp;
}
return preNode;
}
};
回文链表(用快慢指针)
最新推荐文章于 2024-10-13 11:38:49 发布