给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。 输入:head = [1,2,2,1] 输出:true…
- User
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
输入:head = [1,2,2,1] 输出:true
输入:head = [1,2] 输出:false
请补充这一段代码: class Solution { public: bool isPalindrome(ListNode* head) { }}
Assistant
这道题要判断链表是否为回文链表。我提供一个时间复杂度O(n)、空间复杂度O(1)的解法:
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; // 1. 使用快慢指针找到链表中点 ListNode* slow = head; ListNode* fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } // 2. 反转后半部分链表 ListNode* secondHalf = reverseList(slow->next); slow->next = nullptr; // 断开前后两部分 // 3. 比较前半部分和反转后的后半部分 ListNode* p1 = head; ListNode* p2 = secondHalf; bool result = true; while (p2) { // 后半部分可能比前半部分少一个节点 if (p1->val != p2->val) { result = false; break; } p1 = p1->next; p2 = p2->next; } // 4. 恢复链表结构(可选) slow->next = reverseList(secondHalf); return result; } private: ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } };
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.