写在前面: 和昨天写的链表题一样,昨天是通过后半段链表逆序+快慢指针求解,今天是通过前半段链表逆序+快慢指针实现的。
- 和昨天不同的是,昨天的写法不需要考虑中间节点是奇是偶的问题,因为是两头往中间跑,但是今天的写法是中间往两头跑,所以要判断奇数的情况
- 欢迎关注我的 力扣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;
};