LeetCode-234-回文链表-C语言

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

/* 
 * 算法思想: 
 * 将list后半段反转,与前半段相比较,如果相同则为回文
 * 否则返回false
 */

typedef struct ListNode Node;
/* 反转链表 */
Node *reverse(Node *head){
    Node node;
    node.next = NULL;
    Node *last = NULL;
    
    while(head){
        last = head;
        head = head->next;
        last->next = node.next;
        node.next = last;
    }
    
    return node.next;
}

/* 比较链表,不考虑最后一个节点,因为长度最长差1,即使差1,也可以回文 */
bool list_cmp(Node *l1, Node *l2){
    while(l2 && l1){
        if(l2->val != l1->val){
            return false;
        }
        l1 = l1->next;
        l2 = l2->next;
    }
        
    return true;
}

bool isPalindrome(struct ListNode* head){
    Node *p = head;
    Node *q = head;
    
    if(!p || !p->next){
        return true;
    }
    
    /* 快慢指针找中点,中点为q
     * 1 2 3 4 中点为3,
     * 1 2 3 4 5中点为3
     */
    while(p){
       q = q->next;
       p = p->next ? p->next->next : p->next;
    }
    
    q = reverse(q);
    
    return list_cmp(q, head);
}


猜你喜欢

转载自blog.csdn.net/weixin_36094222/article/details/90046103