标签:node div als flag break span 比较 amp slow
bool isPalindrome(ListNode* head) { ListNode* fast = head; ListNode* slow = head; //如果没有元素 if(head==NULL) return true; //如果就一个元素 if(fast->next==NULL) return true; //如果就两个元素 if(fast->next->next==NULL) return fast->val == fast->next->val; //上面已经进行了边界条件的判断,下面保证至少有3个元素以上 //如果超过了两个元素 while(fast->next!=NULL && fast->next->next!=NULL) { slow = slow->next; fast = fast->next->next; } //如果是奇数,slow指向中间的值,如果是偶数,slow指向中间的前一个数 fast = slow->next; slow->next = NULL; ListNode *tmp = NULL; while(fast!=NULL) { tmp = fast->next; fast->next = slow; slow = fast; fast = tmp; } //开始进行比较 fast = slow; tmp = head; bool flag = true; //这个条件判断很重要 while(fast!=NULL && tmp!=NULL) { if(fast->val != tmp->val) { flag = false; break; } fast = fast->next; tmp = tmp->next; } //对链表再次进行翻转 fast = slow->next; slow->next = NULL; tmp = NULL; while(fast!=NULL) { tmp = fast->next; fast->next=slow; slow = fast; fast = tmp; } return flag; }
标签:node div als flag break span 比较 amp slow
原文地址:https://www.cnblogs.com/randyniu/p/9462133.html