234. Palindrome Linked List LeetCode

来源:互联网 发布:我们来了网络几点更新 编辑:程序博客网 时间:2024/06/09 00:11

题意:判断一个链表是不是回文链表。
题解:slow和fast双指针,slow走一步,fast走两步。最后slow在链表的中间。然后将后半部分链表翻转,然后链表头和翻转后的部分开始一一比较。

class Solution {public:    ListNode* reverseList(ListNode* head) {        ListNode *pre = NULL;        ListNode *cur = head;        while(cur != NULL)        {            ListNode *next = cur->next;            cur->next = pre;            pre = cur;            cur = next;        }        return pre;    }    bool isPalindrome(ListNode* head) {        ListNode* slow,* fast;        slow = fast = head;        while(fast && fast->next)        {            slow = slow->next;            fast = fast->next->next;        }        if(fast)        {            slow->next = reverseList(slow->next);            slow = slow->next;        }        else            slow = reverseList(slow);        while(slow)        {            if(slow->val != head->val) return false;            slow = slow->next;            head = head->next;        }        return true;    }};
0 0