RT
14. 判断单链表是否为回文链表
hi,可以不用先遍历一次链表计算len,增加一个快指针,如下:
bool isPalindrome(ListNode* head) {
if (head == NULL) {
return true;
}
if (head->next == NULL) {
return true;
}
ListNode* p = head;
ListNode* cur = head->next;
ListNode* fast = head->next->next;
while(fast != NULL && fast->next != NULL) {
p->next = cur->next;
cur->next = head;
head = cur;
cur = p->next;
fast = fast->next->next;
}
if (fast != NULL) {
cur = cur->next;
}
ListNode* p1 = head;
while(cur != NULL) {
if (p1->val != cur->val) {
return false;
}
p1 = p1->next;
cur = cur->next;
}
return true;
}