LeetCode 234 Palindrome Linked List
题干:
给定一个链表,判断是否是回文链表。
Input: head = [1,2,2,1]
Output: true
--------
Input: head = [1,2,1]
Output: true
解:
时间复杂度为O(n),空间复杂度为O(1)。
ListNode* getMid(ListNode* head){ //找中间(偶数个选靠前的版)
ListNode dummy(-1, head);
ListNode* fast = &dummy, *slow = &dummy;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* reverseList(ListNode* head){ //反转链表
ListNode* prev = nullptr, *cur = head;
while(cur){
ListNode* tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
bool isPalindrome(ListNode* head) {
ListNode* prev = head;
ListNode* mid = getMid(head);
ListNode* after = reverseList(mid->next);
while(after){
if(prev->val != after->val) return false;
prev = prev->next;
after = after->next;
}
return true;
}