Given a singly linked list, determine if it is a palindrome.
Ideas:
Use the fast and fast pointer to find the midpoint of the list, reverse the second half of the list, and then match the first half, then the linked list back to the original (the subject does not have this requirement, concrete case specific treatment).
C++:
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 Alistnode* reverselist (ListNode *listhead) - { -ListNode *prenode =NULL; theListNode *curnode =Listhead; -ListNode *reversehead =NULL; - - while(Curnode! =NULL) + { -ListNode *nextnode = curnode->Next; + A if(NextNode = =NULL) at { -Reversehead =Curnode; - } - -Curnode->next =Prenode; -Prenode =Curnode; inCurnode =NextNode; - } to + returnReversehead; - } the * BOOLIspalindrome (listnode*head) { $ Panax Notoginseng if(Head = =0|| Head->next = =0) - return true; the +ListNode *P1 =head; AListNode *P2 =head; the while(P2->next! =0&& P2->next->next! =0) + { -P1 = p1->Next; $P2 = p2->next->Next; $ } - -ListNode *rhead = reverselist (p1->next); theP1->next =0; - WuyiP1 =head; theP2 =Rhead; - while(P2! =0) Wu { - if(P2->val! = p1->val) About return false; $ -P1 = p1->Next; -P2 = p2->Next; - } A +P1 =head; the while(P1->next! =0) -P1 = p1->Next; $ theListNode *mhead =reverselist (rhead); theP1->next =Mhead; the the return true; - } in};
"Leetcode 234" palindrome Linked List