Source: Internet
Author: User

Test instructions: Given a single linked list, determine whether the linked list is a palindrome. Time complexity required O (N), Space complexity of O (1)

is also an easy topic, but because the data structure compared slag, before the link list reversal problem, write down this algorithm here.

The idea is to find the middle of the list, reverse the second half of the list, the complexity is O (n), in O (n) traversal to see if the front half is the same, so the total complexity is O (n).

The code for the list reversal is:

1 tmp = List-- next; 2  while (List-and next! = NULL) {3 p = tmp- next; 4 tmp-next = P- next; 5 P-Next = List-- next; 6 List--next = p        ; 7 }

Here, the list is the previous node of the linked list to be reversed, list-and next points to the first element to be reversed, for example, a linked list A, B, C, and D, which you want to invert to a, C, B,

Then using the above algorithm is the structure of list, A, B, C and D, and then according to the principle of code, once put the b,c,d at the front, the rest of the structure is unchanged, the specific process is:

b, C, C, B, B-------------------D ==> C-------->d A.

So this problem is very simple, the AC code is as follows:

classSolution { Public:    BOOLIspalindrome (listnode*head) {        intn =0; ListNode*pos =Head;  while(POS! =NULL) {N++; POS= posNext; }        if(n = =0|| n = =1)            return true; N= N/2-((n%2) ^1); POS=Head;  for(inti =0; I < n; i++) {pos= posNext; } ListNode*list =POS; ListNode* TMP = pos-Next;  while(tmp-> Next! =NULL) {ListNode*p = tmp->Next; TMPNext = P-Next; PNext = ListNext; ListNext =p; } ListNode*H1 = ListNext;  while(H1! =NULL) {            if(H1, Val! = Headval) {                return false; } H1= H1Next; Head= HeadNext; }        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.