翻转链表

Leetcode 234

原题链接:https://leetcode.com/problems/palindrome-linked-list/

原题代码:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL) return true;
        ListNode* slow = head;
        ListNode* quick = head;
        //使用快慢指针找到数组的后半部分第一个指针
        while(quick != NULL && quick->next != NULL)
        {
            slow = slow->next;
            quick = quick->next->next;
        }
        //通过迭代法来反转后半部分链表
        ListNode* pre = NULL;
        ListNode* cur = slow;
        while(cur != NULL)
        {
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        //此时的pre指向的链表最后一个节点
        while(pre != NULL)
        {
            if(pre->val != head->val)
                return false;
            pre = pre->next;
            head = head->next;
        }
        return true;
    }

};

 

posted @ 2020-09-22 08:26  锤子科技未来产品经理  阅读(86)  评论(0)    收藏  举报