0%

palindrome-linked-list

Palindrome Linked List – LeetCode 234

Problem

Description

Given a singly linked list, determine if it is a palindrome.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head || !head->next) return true;

ListNode *slow = head;
ListNode *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}

ListNode *curr = slow->next;
slow->next = nullptr; //important!!!
fast = curr? curr->next: nullptr;
while(curr) {
curr->next = slow;
slow = curr;
curr = fast;
fast = fast? fast->next: nullptr;
}

while(slow){
if(head->val == slow->val){
head = head->next;
slow = slow->next;
} else
return false;
}

return true;
}
};

思路

先是使用快慢双指针法找到中间节点,然后将后半部分翻转,再从头尾对应检验val的值。相当于之前几道题的一同考察,时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$19$ ms,排名$56.02\%$

Better

思路

还没看到更好的思路。