--- title: 'LeetCode 234. Palindrome Linked List' disqus: hackmd --- # LeetCode 234. Palindrome Linked List ## Description Given the head of a singly linked list, return true if it is a palindrome. ## Example Input: head = [1,2,2,1] Output: true ## Constraints The number of nodes in the list is in the range [1, 10^5^]. 0 <= Node.val <= 9 ## Answer 此題可先用slow & fast抓中間點,然後從中間做反轉,最後一一比對值有無相同。 ```Cin= bool isPalindrome(struct ListNode* head){ if(head == NULL){return false;} if(head->next == NULL){return true;} struct ListNode *slow = head->next, *fast = head->next->next; struct ListNode *cur = NULL, *nxt = NULL, *opr = NULL; while(fast != NULL && fast->next != NULL){ slow = slow->next; fast = fast->next->next; } opr = slow; while(opr != NULL){ nxt = opr->next; opr->next = cur; cur = opr; opr = nxt; } while(cur != NULL){ if(cur->val == head->val){ cur = cur->next; head = head->next; } else{ return false; } } return true; } ``` ## Link https://leetcode.com/problems/palindrome-linked-list/ ###### tags: `Leetcode`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up