[LeetCode][算法初级][链表]45 回文链表

 
 

这道题反而递归的算法比较容易想到了,首先要先递归到链表的末尾,再递归返回时与链表头的元素开始比较。

感觉还有优化的空间,比如当tail和front交汇时停止比较?但是反而递归的算法不太容易操作..

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* func(struct ListNode**front,struct ListNode* tail);
bool isPalindrome(struct ListNode*  head) {
    struct ListNode*  front = head;
    struct ListNode*  tail = head;
    if(head==NULL||head->next==NULL)
        return true;
    struct ListNode* ret = func(&front,tail);
    if(ret)
        return true;
    else
        return false;
}


struct ListNode* func(struct ListNode**front,struct ListNode* tail){ //为了能吧对front的操作贯穿递归调用,而用的指针的指针
    struct ListNode* ret=NULL;
    if(tail->next){
        ret = func(front,tail->next);
        if(ret&&tail->val == (*front)->val){
            *front=(*front)->next ;
            return tail;
        }else{
            return NULL;
        }
    }else{
        if(tail->val == (*front)->val){
            *front=(*front)->next ;
            return tail;
        }else{
            return NULL;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lokira518/article/details/80341424