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