力扣算法题-234.回文链表

题目

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list

思路

1、首先获取链表长度;
2、获取前段链表,和后段链表;
3、翻转后段链表,若前段和后段链表遍历全部相等,则为回文链表,否则不是;

程序

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


bool isPalindrome(struct ListNode* head){
    
    
    int n = 0,icnt = 0;
    struct ListNode* node = head;
    struct ListNode* thead = NULL;
    struct ListNode* tnode = NULL;
    struct ListNode* tpre = NULL;
    struct ListNode* tnext = NULL;
    /*获取链表长度*/
    while(node != NULL){
    
    
        icnt++;
        node = node->next;
    }
    /*遍历节点到中点*/
    node = head;
    while(n != (icnt/2)){
    
    
        n++;
        node=node->next;
    }
    /*若存在余数,则多遍历一个*/
    if(icnt%2){
    
    
        thead = node->next;
    }else{
    
    
        thead = node;
    }
    /*翻转剩余链表字节*/
    tnode= thead;
    while(tnode != NULL){
    
    
        tnext = tnode->next;
        tnode->next = tpre;

        tpre = tnode;
        tnode = tnext;
    }
    /*链表对比,若存在值不相等,则不是回文链表,否则就是*/
    tnode = tpre;
    node = head;
    while(tnode != NULL && node != NULL){
    
    
        if(tnode->val != node->val){
    
    
            return false;
        }
        tnode=tnode->next;
        node = node->next;
    }
    return true;
}

おすすめ

転載: blog.csdn.net/MDJ_D2T/article/details/109252380