OJ. Determine whether the linked list is a palindrome

Idea: First find the intermediate node of the linked list, then reverse the linked list from the second half after the intermediate node; then compare the first half and the second half one by one.

//The establishment of the linked list
struct ListNode { int val; struct ListNode *next; };


bool isPalindrome(struct ListNode* head)
{ //Find the intermediate node struct ListNode two=head, one=head; while(two&&two->next) { one=one->next; two=two->next->next; } //Invert the second half struct ListNode newhead = NULL; struct ListNode Next = NULL; struct ListNode* cur = one; while (cur) { Next = cur->next; cur->next = newhead; newhead = cur ; cur = Next; } //Compare one by one, return true if it is a palindrome structure; return false if it is not. while (head&&newhead) { if (head->val != newhead->val) return false;























newhead = newhead->next;
head = head->next;
}
return true;
}

Guess you like

Origin blog.csdn.net/qq_43745617/article/details/111319776