234. Palindrome Linked List

判断链表是否满足回文标准:将链表分为二段,前一半正常不动,后一半进行反转,然后遍历前半段和后半段的链表节点元素,逐一比对元素属性值,判断是否满足回文标准。

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head==NULL)
        {
            return 1;
        }
        
        ListNode *mid=head,*right=head;
        int node=1;
        while(right->next!=NULL)
        {
            right=right->next;  //point to the last node
            node++;
        }
         
        for(int i=0;i<node/2;i++)
            mid=mid->next;  //mid points to the mid-node
       // mid=mid->next; 
        
        ListNode *temp=(ListNode*)malloc(sizeof(ListNode)); // the head of the new list
        temp->next=NULL;  //the head node is null
        
        while(mid!=NULL)
        {
            ListNode *flag=(ListNode*)malloc(sizeof(ListNode));
            flag->val=mid->val;
            flag->next=temp->next;
            temp->next=flag;  
            
            mid=mid->next;
            
        } //reverse the last part of the link-list
        
        temp=temp->next;  // the val of head node is null ,so points to the next node of the head node
        
        while(temp!=NULL)
        {
            if(temp->val!=head->val)
                return 0;
            else
            {
                temp=temp->next;
                head=head->next;
            }
        }  //link-list node matching 
        return 1;
       
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值