leetcode 日经贴,Cpp code -Palindrome Linked List

Palindrome Linked List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (!head || !head->next) {
            return true;
        }
        //find the mid node
        ListNode *h1 = head, *h2 = head;
        while (h2 && h2->next) {
            h1 = h1->next;
            h2 = h2->next->next;
        }
        //reverse the second part
        ListNode *h3 = h2? h1->next: h1;
        h2 = h3->next;
        h3->next = NULL;
        while (h2) {
            h1 = h2->next;
            h2->next = h3;
            h3 = h2;
            h2 = h1;
        }
        h1 = head;
        while (h3) {
            if (h3->val != h1->val) {
                return false;
            }
            h3 = h3->next;
            h1 = h1->next;
        }
        return true;
    }
};


阅读更多
个人分类: 算法 Cpp leetcode
上一篇leetcode 日经贴,Cpp code -Number of Digit One
下一篇python logging
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭