LeetCode Palindrome Linked List

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Palindrome Linked List相关的知识,希望对你有一定的参考价值。

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;
    }
};

 

以上是关于LeetCode Palindrome Linked List的主要内容,如果未能解决你的问题,请参考以下文章

Palindrome Number ---- LeetCode 009

leetcode 9. palindrome number

LeetCode-Valid Palindrome

LeetCode:Palindrome Number

LeetCode Longest Palindrome

[Leetcode] Palindrome Number