题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
代码实现
两种思路:
- 用栈实现,前半部分入栈,后半部分判断和当前栈顶的数,不相等则不是回文链表,相等则出栈,继续判断。时间复杂度O(n),空间复杂度O(n)。
- 快慢指针,快指针到达最末端时慢指针到中间位置,前半部分链表翻转,然后判断前半部分和后半部分是否一样。时间复杂度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 == NULL) return true;
stack<int> p;
ListNode* l = head;
int n = 0;
while(l != NULL){
l = l->next;
n++;
}
int flag = n % 2;
int count = 0;
l = head;
while(l != NULL){
if(count < n/2) p.push(l->val);
else{
if(flag && count == n/2);
else{
if( l->val == p.top()) p.pop();
else return false;
}
}
count++;
l = l->next;
}
if(p.empty()) return true;
else return false;
}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
ListNode* slow = head;
ListNode* fast = head;
ListNode* pre = NULL;
ListNode* s = NULL;
while(fast != NULL && fast->next != NULL)
{
pre = slow;
slow = slow->next;
fast = fast->next->next;
pre->next = s;
s = pre;
}
if(fast != NULL) slow = slow->next;
while(slow != NULL && pre != NULL){
if(slow->val != pre->val) return false;
slow = slow->next;
pre = pre->next;
}
return true;
}
};