Leetcode-palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could do it in O (n) time and O (1) space?
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: One BOOLIspalindrome (listnode*head) { A if(head = = NULL | | head->next = = NULL)return true; - if(Head->next->next = =NULL) { - if(Head->val = = Head->next->val)return true; the Else return false; - } -listnode* TP1 =head; -listnode* TP2 =head; + while(Tp2->next! = NULL && Tp2->next->next! =NULL) { -TP1 = tp1->Next; +TP2 = tp2->next->Next; A } atlistnode* mid = Tp1->Next; -listnode* P1 =head; -listnode* P2 =reverse (mid); - while(P2! =NULL) { - if(P2->val! = p1->val)return false; - Else{ inP1 = p1->Next; -P2 = p2->Next; to } + } - return true; the } *listnode* Reverse (listnode*mid) { $ if(Mid->next = = NULL)returnmid;Panax Notoginsenglistnode* now =mid; -listnode* prev =NULL; the while(Now! =NULL) { +listnode* TP = now->Next; ANow->next =prev; thePrev =Now ; +now =TP; - } $ returnprev; $ } -};
Two methods, one is to find the middle node, and then put the following data into the vector, and then compare, the space complexity of O (n);
The other is to find the middle node, then reverse the list, then compare the spatial complexity of O (1).
Note that the middle node is used with two pointers, one at a time, the other walking twice, so that the last one reaches the end or the penultimate, and the front pointer points to the end of the first half or the middle node (in relation to the parity). This will allow you to find the starting position of the latter half.
Then the latter half is reversed. This takes three pointers, pointing to the previous node, the current node, and the latter node each time, pointing to the previous node with the next pointer of the current node, and then updating three pointers. Until the current node is null (at the end), the first node at this point is the head junction. It is suggested that drawing be more visually understood.
Leetcode-palindrome Linked List