leetcode 日经贴,Cpp code -Palindrome Linked List

来源:互联网 发布:淘宝查号 编辑:程序博客网 时间:2024/06/08 07:28

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


0 0