请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解答
找到中间节点,翻转后半段链表,再逐个进行对比:
/**
* 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* mid = middle(head);
ListNode* h2 = mid->next;
mid->next = nullptr;
h2 = reverse(h2);
while(head && h2){
if(head->val != h2->val)
return false;
head = head->next;
h2 = h2->next;
}
return true;
}
ListNode* middle(ListNode* node){
ListNode *slow, *fast;
slow = fast = node;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverse(ListNode* node){
ListNode *pre, *cur, *next;
pre = nullptr;
cur = next = node;
while(cur){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
递归:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* front;
bool isPalindrome(ListNode* head) {
if(!head || !head->next)
return true;
front = head;
return helper(head);
}
bool helper(ListNode* node){
if(!node)
return true;
else{
if(!helper(node->next))
return false;
// 执行到此处时,front正好是node对称位置处的节点
if(front->val != node->val)
return false;
front = front->next;
return true;
}
}
};