题解:
直接看代码。
代码:
/**
* 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) {
/* 方法1:用数组记录元素 O(n)的时间 O(n)的空间
vector <int> vec;
while(head)
{
vec.push_back(head->val);
head = head->next;
}
int len = vec.size();
for(int i = 0; i < len/2; i++)
{
if(vec[i] != vec[len-i-1])
{
return false;
}
}
return true;*/
/* 方法2:用栈记录元素 O(n)的时间 O(1)的空间
stack <int> stk;
ListNode* tmp = head;
while(tmp)
{
stk.push(tmp->val);
tmp = tmp->next;
}
while(!stk.empty())
{
if(stk.top() != head->val)
{
return false;
}
stk.pop();
head = head->next;
}
return true;*/
/* 方法3:快慢指针 O(n)的空间 O(1)的时间 */
if(head == NULL)
{
return true;
}
ListNode* fast;
ListNode* slow;
fast = slow = head;
while(fast->next != NULL && fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
// 把slow->next开始的节点作为一个链表,然后反转过来(head2作为反转链表的第一个节点)
ListNode* head2 = reverse(slow->next);
while(head2 != NULL)// 遍历完反转链表(后半部分),顺便和前半部分比较
{
if(head->val != head2->val)
{
return false;
}
head = head->next;
head2 = head2->next;
}
return true;
}
ListNode* reverse(ListNode* head)
{
if(head == NULL || head->next == NULL)
{
return head;
}
else
{
ListNode* res = reverse(head->next);
head->next->next = head;
head->next = NULL;
return res;
}
}
};