回文链表
题目
请判断一个链表是否为回文链表。
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
示例1:
输入: 1->2
输出: false
示例2:
输入: 1->2->2->1
输出: true
解决
1.空间与时间占用均较大-快慢指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *fast = head , *slow = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
if(fast != NULL){
slow = slow->next;
}
fast = reverse(slow);
slow = head;
while(fast != NULL){
if(fast->val != slow->val) return false;
fast = fast->next;
slow = slow->next;
}
return true;
}
ListNode* reverse(ListNode *head){
ListNode *cur = head;
ListNode *pre = head;
ListNode *end = NULL;
while(cur != NULL){
pre = cur;
cur = cur->next;
pre->next = end;
end = pre;
}
return end;
}
};
总结
O(n) 时间复杂度和 O(1) 空间复杂度,虽然符合题目但是程序并不够好,还待优化。