Palindrome Linked List

Source: Internet
Author: User

Title Description:
if  is   do in O (n) Time and O (1) space?

The idea is to reverse the first or second half of a single-linked list, and then compare it.

Solution:

BOOLIspalindrome (listnode*head) {    if(head = = NULL | | head->next = =NULL)return true; ListNode*fast =Head; ListNode*slow =Head;  while(Fast->next! =NULL) {Fast= fast->Next; Slow= slow->Next; if(Fast->next! =NULL) Fast= fast->Next; } Fast=reverselist (slow); ListNode*p =Head;  while(P! = Slow && P->val = = fast->val) {P= p->Next; Fast= fast->Next; }    if(p = =slow)return true; Else        return false;}

Reverse the single-linked list code see here

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.