234. 回文链表 - 力扣(LeetCode) (leetcode-cn.com)
1 class Solution { 2 public: 3 bool isPalindrome(ListNode* head) { 4 if (head == nullptr || head->next == nullptr) return true; 5 ListNode* slow = head; // 慢指针,找到链表中间分位置,作为分割 6 ListNode* fast = head; 7 while (fast && fast->next) {//12的话 ,1 2;123的话,1,23;1234的话,1 8 slow = slow->next; 9 fast = fast->next->next; 10 } 11 if(fast)//奇数,1 ,23,23变成3再反转 12 slow = slow->next; 13 14 ListNode* cur1 = head; // 前半部分 15 ListNode* cur2 = reverseList(slow); // 16 17 // 开始两个链表的比较 18 while (cur1&&cur2) { 19 if (cur1->val != cur2->val) return false; 20 cur1 = cur1->next; 21 cur2 = cur2->next; 22 } 23 return true; 24 } 25 // 反转链表 26 ListNode* reverseList(ListNode* head) { 27 ListNode* temp; // 保存cur的下一个节点 28 ListNode* cur = head; 29 ListNode* pre = nullptr; 30 while(cur) { 31 temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next 32 cur->next = pre; // 翻转操作 33 // 更新pre 和 cur指针 34 pre = cur; 35 cur = temp; 36 } 37 return pre; 38 } 39 };