The palindrome structure of the linked list

Source: Internet
Author: User

Title Description

For a linked list, design a time complexity of O (n), additional space complexity is O (1) algorithm, to determine whether it is a palindrome structure.

Given the head pointer a of a linked list, return a bool value that indicates whether it is a palindrome structure. Ensure that the list length is less than or equal to 900.

Test examples:
1->2->2->1
Return: True

/*struct ListNode {int val;    struct ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};*/classPalindromelist { Public:    BOOLChkpalindrome (listnode*A) {//Write code here        if(A = = NULL)return false; BOOLFlag =true; ListNode*firstnode =A; ListNode*secondnode =A;  while(Secondnode->next! =NULL) {Secondnode= secondnode->Next; }                 while(Firstnode <Secondnode) {            if(Firstnode->val! = secondnode->val) {Flag=false;  Break; } Firstnode= firstnode->Next; Secondnode=Updatesecondnode (A, Secondnode); }        returnFlag; } ListNode* Updatesecondnode (ListNode *a, ListNode *Secondnode) {ListNode*prenode =A;  while(Prenode->next! =Secondnode) {Prenode= prenode->Next; }        returnPrenode; }};

Solution 2: (implemented with stacks)



The palindrome structure of the 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.