The idea isn't so obvious at first glance. Since-cannot move from a node-to-its-previous node in a singly linked list, we choose-reverse the right half O f the list and then compare it with the left half. The code is as follows. It Shoul is obvious after you run some examples.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: One BOOLIspalindrome (listnode*head) { A if(!head | |! (Head-to-next))return true; -listnode* slow =head; -listnode* fast =head; the while(Fast && fastnext) { -slow = slowNext; -Fast = fast, NextNext; - } + if(FAST) { -Slow-next = reverselist (Slow-next); +slow = slowNext; A } at Elseslow =reverselist (slow); - while(slow) { - if(Head, Val! = Slowval) - return false; -Head = HeadNext; -slow = slowNext; in } - return true; to } + Private: -listnode* Reverselist (listnode*node) { thelistnode* pre =NULL; * while(node) { $Listnode* Next = node-Next;Panax NotoginsengNode-next =Pre; -Pre =node; thenode =Next; + } A returnPre; the } +};
[Leetcode] Palindrome Linked List