234.回文链表

思路:(1)可以将链表分为两半,list1和list2。如何分成两半,就用快慢指针找到中间节点。

           (2) 将list2逆置。

           (3)将list1和list2进行比较,如果相等,就是回文链表,如果不相等,就不是。

            如果是奇数个,就比较到list1完就停止。

struct ListNode* reverse(struct ListNode* head)  //逆置
{  
    struct ListNode*cur=head;
    struct ListNode*prev=NULL;
    while(cur)
    { struct ListNode* next=cur->next;
    cur->next=prev;
    prev=cur;
    cur=next;
    } 
    return prev;
}
bool isPalindrome(struct ListNode* head){
    if(head==NULL||head->next== NULL)
    {
         return true;
    }
   
   struct ListNode* cur=head;
struct ListNode* slow=head;
struct ListNode* fast=head;
struct ListNode* prev=NULL;
while(fast&&fast->next)//寻找中间节点
{    prev=slow;
    slow=slow->next;
    fast=fast->next->next;
}
     prev->next=NULL; //前一半最后节点的next指向空
     struct ListNode* newmiddle= reverse(slow);
     struct ListNode* cur1=newmiddle;
     while(cur) //比较
     {
         if(cur->val!=cur1->val)
         return false;
         else{
               cur=cur->next;
         cur1=cur1->next;
         }
       
     }
return true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值