[LeetCode]234. Palindrome Linked List 解题报告(C++)
题目描述
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
题目大意
- 检查给定的单链表是否是
回文
- 时间复杂度 O(n) 空间复杂度O(1)
解题思路
方法1:
- 通过 栈存储前一半. 用快慢指针遍历一半.
- 遍历后面一半.. 从栈中取出看是否与后面一半的相同
- 空间复杂度并非 O(1)
代码实现:
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow, *fast;
slow = head; fast = head;
stack<int> s;
while (fast&&fast->next) {
s.push(slow->val);
slow = slow->next;
fast = fast->next->next;
}
if (fast) {
while (slow->next) {
slow = slow->next;
int tmp = s.top(); s.pop();
if (tmp != slow->val) {
return false;
}
}
}
else {
while (slow) {
int tmp = s.top(); s.pop();
if (tmp != slow->val) {
return false;
}
slow = slow->next;
}
}
return true;
}
};
方法2:
- reverse链表.
代码实现:
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)
return true;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
slow->next=reverseList(slow->next);
slow=slow->next;
while(slow!=NULL){
if(head->val!=slow->val)
return false;
head=head->next;
slow=slow->next;
}
return true;
}
ListNode* reverseList(ListNode* head) {
ListNode* pre=NULL;
ListNode* next=NULL;
while(head!=NULL){
next=head->next;
head->next=pre;
pre=head;
head=next;
}
return pre;
}
};
小结
- 这一题有一个疑问!!!
- 翻转链表的空间复杂度到底是 O(n) 还是 O(1)