码迷,mamicode.com
首页 > 其他好文 > 详细

234 回文链表

时间:2019-01-12 18:58:59      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:lis   false   next   ali   tno   fas   链表   cpp   lse   

ListNode *reverse(ListNode *head) {
    ListNode *front = head, *rear = nullptr, *temp = nullptr;
    while (front != nullptr) {
        temp = front->next;
        front->next = rear;
        rear = front;
        front = temp;
    }
    return rear;
}

ListNode *middleNode(ListNode *head) {
    ListNode *slow = head;
    ListNode *fast = head;
    while (fast != nullptr && fast->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return fast == nullptr ? slow : slow->next;
}

bool isPalindrome(ListNode *head) {
    ListNode *mid = middleNode(head);
    ListNode *re = reverse(mid);
    while (re != nullptr) {
        if (re->val != head->val)
            return false;
        re = re->next;
        head = head->next;
    }
    return true;
}

234 回文链表

标签:lis   false   next   ali   tno   fas   链表   cpp   lse   

原文地址:https://www.cnblogs.com/INnoVationv2/p/10260558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!