題解:
直接看代碼。
代碼:
/**
* 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;
}
}
};