/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class PalindromeList { public: bool chkPalindrome(ListNode* A) { // *** 处理空链表 *** ListNode* cur = A; if(!cur){return true;} // *** 链表找中 *** ListNode* fast = cur; ListNode* slow = cur; while(fast && fast->next) { // 确保fast最终指向队尾非空节点 if(fast->next->next) { fast = fast->next->next; } else { fast = fast->next; } slow = slow->next; }// fast->next一定为空 ListNode* mid = slow; // *** 后半段链表反转 *** cur = slow->next; ListNode* index = cur->next; // 标记原链表中cur遍历到的位置 auto* right_head = new ListNode(1); while(cur != nullptr) { ListNode* tmp = right_head->next; cur->next = tmp; right_head->next = cur; cur = index; if (index) { index = index->next; } } mid->next = right_head->next; // 链接两链表 delete right_head; // *** 遍历前后两部分链表 *** fast = mid->next; slow = A; while(fast) { if(fast->val != slow->val) { return false; } fast = fast->next; slow = slow->next; } return true; } };
本方法采用对整个链表后半部分进行反转,再分别以头结点和链表中间节点的下一个节点作为两子链表的头节点,遍历比较两链表中值是否始终相等,如果不等立马return返回false,即非回文链表。