给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
时间复杂度较大的解法:
/*** 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:ListNode* reverseList(ListNode* head){ListNode* pre=nullptr;ListNode* cur=head;while(cur){ListNode* tmp = cur->next;cur->next = pre;pre = cur;cur=tmp;}return pre;}bool isPalindrome(ListNode* head) {if(head->next == nullptr) return true;// 找到中间节点ListNode* fast = head;ListNode* slow = head;// fast向前的速度是slow的2倍while(fast!=nullptr){fast = fast->next;if(fast!=nullptr){fast = fast->next;}slow = slow->next;}// 翻转链表ListNode* backlist = reverseList(slow);// 依次比较两链表while(backlist){if(head->val != backlist->val)return false;head= head->next;backlist=backlist->next;}return true;}
};