题目描述:
给一个单链表,判断是否是回文的。
要求时间复杂度:O(n),空间复杂度:O(1)。
思路:
反转一半链表,然后依次比较。
但是不知道为什么提交RE,,,返回的case都测过了。。。。
代码:
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL) return true;
ListNode* slow = head;
ListNode* fast = head;
ListNode* firstHalf = NULL;
ListNode* secondHalf = NULL;
while(fast != NULL && fast->next != NULL) {
firstHalf = slow;
slow = slow->next;
fast = fast->next->next;
secondHalf = slow->next;
}
if (fast == NULL) secondHalf = slow;
cout << "---------------\n";
firstHalf->next = NULL;
ListNode* pre = head;
ListNode* nxt = head->next;
while(nxt != NULL && pre!=NULL) {
ListNode* temp = nxt->next;
nxt->next = pre;
pre = nxt;
nxt = temp;
}
cout << "================\n";
ListNode* head2 = secondHalf;
head = pre;
while(head != NULL && head2 !=NULL){
if (head->val != head2->val) {
return false;
}
head = head->next;
head2 = head2->next;
}
cout << ".........................\n";
return true;
}
};