题目描述:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路:
这道题采用的是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) {
//O(n) 时间复杂度和 O(1) 空间复杂度,但是缺点是会修改链表的结构
if(head == nullptr || head->next == nullptr) return true;
ListNode* pslow = head, *pfast = head;
while(pfast->next){
pslow = pslow->next;
pfast = pfast->next->next;
if(pfast == nullptr)
break;
}
//此时的pslow在链表中间的位置
ListNode* pre = pslow, *temp = nullptr;
pslow = pslow->next;
pre->next = nullptr;
while(pslow){
temp = pslow->next;
pslow->next = pre;
pre = pslow;
pslow = temp;
}
ListNode* first = head, *end = pre;
while(first != end){
if(first->next == end){
if(first->val == end->val) return true;
else return false;
}
if(first->val == end->val){
first = first->next;
end = end->next;
}
else{
return false;
}
}
return true;
}
};