题目
解法1:
新建一个反转的链表,然后与原链表比较
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* prev = NULL;
ListNode* tmp = head;
while(tmp){
ListNode* curr = new ListNode(tmp->val);
curr->next = prev;
prev = curr;
tmp = tmp->next;
}
while(prev){
if(prev->val != head->val){
return false;
}
head = head->next;
prev = prev->next;
}
return true;
}
};
解法2:
使用快慢指针找中点,然后反转后半部分列表进行对比
python:
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
def reverse_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
if not head or not head.next:
return True
# find the middle point of the linked list
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
new_head = reverse_list(slow.next)
while new_head:
if head.val != new_head.val:
return False
head = head.next
new_head = new_head.next
return True
C++
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode *new_head = reverse_list(slow->next);
// 这边必须要循环new_head,因为链表中间被断开,后面并没有加空指针,所以用head循环会报错。其次对于奇数节点个数的链表,后半部分的链表会比前半部分少一个节点,所以也必须循环new_head
while(new_head){
if (head->val!=new_head->val) return false;
head = head->next;
new_head = new_head->next;
}
return true;
}
ListNode* reverse_list(ListNode* head){
ListNode *prev = nullptr;
ListNode *curr = head;
while(curr){
ListNode *next_node = curr->next;
curr->next = prev;
prev = curr;
curr = next_node;
}
return prev;
}
};