寫在前面: 和昨天寫的鏈表題一樣,昨天是通過後半段鏈表逆序+快慢指針求解,今天是通過前半段鏈表逆序+快慢指針實現的。
- 和昨天不同的是,昨天的寫法不需要考慮中間節點是奇是偶的問題,因爲是兩頭往中間跑,但是今天的寫法是中間往兩頭跑,所以要判斷奇數的情況
- 歡迎關注我的 力扣github倉庫,有JavaScript和C++兩個版本,每日更新
C++代碼:
/**
* 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 || !head->next)
return true;
ListNode *fast=head,*slow=head;
while(fast && fast->next) //快慢指針找出中點
{
slow=slow->next;
fast=fast->next->next;
}
ListNode *L=new ListNode,*temp,*p=head;
while(p!=slow) //前半部分逆序
{
temp=p->next;
p->next=L;
L=p;
p=temp;
}
if(fast) //這是奇數的情況,慢指針要往後走一位才能對稱
slow=slow->next;
while(L && L->next)
{
if(L->val!=slow->val)
return false;
L=L->next;
slow=slow->next;
}
return true;
}
};
JS代碼:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
if(!head || !head.next)
return true;
var fast=head,slow=head;
while(fast && fast.next)
{
slow=slow.next;
fast=fast.next.next;
}
var L=new ListNode,p=head,temp;
while(p!=slow)
{
temp=p.next;
p.next=L;
L=p;
p=temp;
}
if(fast)
slow=slow.next;
while(L && L.next)
{
if(L.val!=slow.val)
return false;
L=L.next;
slow=slow.next;
}
return true;
};