导航

LeetCode Palindrome Linked List

Posted on 2016-03-29 01:17  CSU蛋李  阅读(144)  评论(0编辑  收藏  举报

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

像1->2->1,1->2->2->1,1,NULL这种都是回文链表。我的思路是找到那个开始回文的点,然后以此为一个链表,再进行链表的翻转。两个链表就可以进行比较了

如1->2->1,从第二个1处开始翻转,1->2->2->1,从第二个2处开始翻转。哎!每次代码都比较多,想不到简单一点的。不过这次的确达到了O(n)的时间复杂度

和O(1)的空间复杂度

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
   ListNode * listReversal(ListNode *head)
    {
        if (!head || !head->next)return head;
        ListNode *mid=head->next,*last=mid->next;
        head->next = NULL;
        for (;last;)
        {
            mid->next = head;
            head = mid;
            mid = last;
            last = last->next;
        }
        mid->next = head;
        return mid;

    }
    bool isPalindrome(ListNode* head) {
if (!head || !head->next)return true;
        ListNode *ptr = head;
        int cnt = 0;
        for (;ptr;ptr = ptr->next, ++cnt);
        cnt = (cnt % 2) ? (cnt / 2 + 2) : (cnt / 2 + 1);
        ptr = head;
        for (int i = 1;i < cnt;++i)
            ptr = ptr->next;
        ptr = listReversal(ptr);
        for (;ptr;ptr = ptr->next, head = head->next)
            if (ptr->val != head->val)return false;
        return true;
    }
};