题意:判断是否为回文链表,要求时间复杂度O(n),空间复杂度O(1)。
分析:
(1)利用快慢指针找到链表的中心
(2)进行步骤(1)的过程中,对前半部分链表进行反转
(3)如果链表长是偶数,首先比较slow和slow->next的值是否相等,若不相等返回false,否则,比较以slow -> next -> next开头的链表和以suf1开头的链表比较是否相等
(4)如果链表长是奇数,则将以slow -> next开头的链表和以suf1开头的链表比较是否相等
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { if(head == NULL) return true; ListNode *fast = head; ListNode *slow = head; ListNode *suf1 = head -> next; ListNode *suf2; while(fast && fast -> next){ fast = fast -> next -> next; suf2 = suf1 -> next; suf1 -> next = slow; slow = suf1; suf1 = suf2; } head -> next = NULL; if(fast){ slow = slow -> next; } else{ if(slow -> val != slow -> next -> val) return false; slow = slow -> next -> next; } while(slow && suf1){ if(slow -> val != suf1 -> val) return false; slow = slow -> next; suf1 = suf1 -> next; } return true; } };