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; }};
Leetcode 234Palindrome Linked List