题解 | #判断一个链表是否为回文结构#c快慢指针找中点,反转后半段链表对比

判断一个链表是否为回文结构

http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f


#include<stdbool.h>
bool isPail(struct ListNode* head ) {
    if(head==NULL||head->next==NULL)
    return true;
    struct ListNode* H=malloc(sizeof(struct ListNode));
    H->next=head;
    struct ListNode *fast=H,*slow=H;
    while(fast!=NULL&&fast->next!=NULL)
    {
      //快慢指针找中点
        fast=fast->next->next;
        slow=slow->next;
    }
    struct ListNode* cur=slow->next;
    slow->next=NULL;
    struct ListNode*q;
    while(cur!=NULL)
    {
      //头插法反转链表
        q=cur;
        cur=cur->next;
        q->next=slow->next;
        slow->next=q;
    }
    while(q!=NULL)
    {
      //对比
        if(q->val==head->val)
        {
            q=q->next;
            head=head->next;
        }
        else
        return false;
    }
    return true;
    // write code here
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务