Source: Internet
Author: User

The requirement of this topic is to determine whether a single linked list is a palindrome list, the difficulty of the topic is O (n) time and O (1) space limitations.

Because the single-linked list can not be reversed, so can not directly through the original linked list to judge, the idea is to solve the original list of the first half of the list to judge, and then to judge (such as the list of "12344321" after the reversal of "43214321"). The realization after this is very simple, and the complete code looks like this:

`Class Solution {public:listnode* reversehalf (listnode* root) {ListNode *fast = root, *slow = Root;//slow points to the reverse section of the latter node while (fast! = nullptr && fast-and next! = nullptr) {fast = fast-Next-& Gt            Next        slow = slow next;        } ListNode *h = new ListNode (0);        H-Next = root;//performs reverse listnode *sec = root, *fir = root-Next;            while (fir! = Slow) {sec-next = fir-next;            Fir-Next = h-Next;            H-next = Fir;        Fir = sec-Next;    } return h-next;        } bool Ispalindrome (listnode* head) {int len = 0;        listnode* p = head;            ListNode *fast, *slow;//calculates the length of the single-linked list while (P! = NULL) {len++;        p = p and next; } if (Len < 2) return true;//reverses the first half of the single-linked list listnode* reversedlist = Reversehalf (head);      Slow point to the middle position of the single-linked list  Fast = slow = reversedlist;            while (fast! = nullptr && fast-next! = nullptr) {fast = fast-next Next;        slow = slow next;        }//fast points to the head of a single-linked list fast = Reversedlist; if (len% 2 = 0) slow = slow-next;//to determine if it is a palindrome string while (slow! = nullptr) {if (Fast, VA            L! = Slow val) return false;            Fast = fast-next;        slow = slow next;    } return true; }};`

Related Keywords:

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.