應該會暫時刷Linked List相關的LeetCode全部的easy題目,等到刷完再換其他類型,都刷完Easy之後,就該挑戰一下Medium~
tags: Easy、Linked-List
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
使用快慢指針來找中間點,當快指針到末端時,代表慢指針走到中間點,並將Linked List拆成兩半(上半部與下半部)進行比對
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head) {
struct ListNode *slow = head;
struct ListNode *fast = head;
if(head->next == NULL) {
return true;
}
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow -> next;
fast = fast -> next->next;
}
struct ListNode *current = slow -> next;
struct ListNode *nextNode = NULL;
struct ListNode *prev = NULL;
slow->next = NULL;
while (current != NULL) {
nextNode = current->next;
current->next = prev;
prev = current;
current = nextNode;
}
struct ListNode *compare = head;
while (prev != NULL) {
if (compare->val != prev->val) {
return false;
}
compare = compare->next;
prev = prev->next;
}
return true;
}