Idea: Reverse the nodes as slow pointer moves forward. Once the fast pointer reaches to the end of the list, then we compare the nodes from where the slow pointer is at and the nodes that are reversed.
Edge cases:
What if the list has odd number of nodes? ex) [1,2,3,4,5]
The method that I used to figure out if the number of nodes is odd or even:
If fast pointer's next exists => even
If fast pointer's next does not exists => odd
When the list has only one node => true (2 does not matter)
classSolution{public:boolisPalindrome(ListNode*head){ListNode*dummy=newListNode();ListNode*slowPrev=dummy,*slow=head,*slowNext=slow,*fast=head;dummy->next=head;boolisOdd=false;while(fast){// Move fast forwardif(fast->next){fast=fast->next->next;}else{fast=fast->next;isOdd=true;}// Reverse slowslowNext=slow->next;slow->next=slowPrev;slowPrev=slow;slow=slowNext;}// Detach dummy node (otherwise will get memory access error)head->next=nullptr;deletedummy;if(isOdd){slowPrev=slowPrev->next;}while(slowPrev&&slow){if(slow->val!=slowPrev->val)returnfalse;slowPrev=slowPrev->next;slow=slow->next;}returntrue;}};
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)