"Leetcode 234" palindrome Linked List

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.