234. 回文链表

链接

思路:先把原来的链表复制一份,再将副本进行翻转,再逐一元素去比较翻转之后的副本和原链表是否相同。

自己写的 C 代码:

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
// 先复制一份,再翻转,再比较是否相同
bool isPalindrome(struct ListNode* head) {
    // 复制
    struct ListNode* copy = (struct ListNode*)malloc(sizeof(struct ListNode));
    copy->val = head->val;
    copy->next = NULL;
    struct ListNode* tail = copy;
    struct ListNode* tmp = head->next;
    while (tmp) {
        struct ListNode* new =
            (struct ListNode*)malloc(sizeof(struct ListNode));
        new->val = tmp->val;
        new->next = NULL;
        tail->next = new;
        tail = new;
        tmp = tmp->next;
    }
    // 翻转
    struct ListNode* prior = NULL;
    struct ListNode* current = copy;
    while (current) {
        struct ListNode* pnext = current->next;
        current->next = prior;
        prior = current;
        current = pnext;
    }
    // 现在翻转之后的链表的首元结点为 prior
    // 逐个比较
    while (prior != NULL && head != NULL) {
        if (prior->val != head->val) {
            return false;
        }
        prior = prior->next;
        head = head->next;
    }
    return true;
}

自己的思路比较繁琐。

官方题解其中之一:

思路:

  1. 复制链表值到数组列表中。
  2. 使用双指针法判断是否为回文。

确定数组列表是否回文很简单,我们可以使用双指针法来比较两端的元素,并向中间移动。一个指针从起点向中间移动,另一个指针从终点向中间移动。这需要 O(n) 的时间,因为访问每个元素的时间是 O(1),而有 n 个元素要访问。

C 代码:

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool isPalindrome(struct ListNode* head) {
    int vals[500001], vals_nums = 0;
    while (head != NULL) {
        vals[vals_nums++] = head->val;
        head = head->next;
    }
    for (int i = 0, j = vals_nums - 1; i < j; ++i, --j) {
        if (vals[i] != vals[j]) {
            return false;
        }
    }
    return true;
}

问题是这个数组要给的足够大,不然不能通过全部的测试用例。

相关推荐
小雨下雨的雨2 小时前
井字棋AI机器人实现详解 - Minimax算法实战-鸿蒙PC Electron框架完成
前端·人工智能·算法·华为·electron·鸿蒙
xieliyu.4 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
明夜之约5 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee5 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Jinkxs5 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
辣机小司5 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
一条小锦吕*5 小时前
基于Spring Boot + 数据可视化 + 协同过滤算法的推荐系统设计与实现(源码+论文+部署全讲解)
spring boot·算法·信息可视化
fangdengfu1236 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
云烟成雨TD6 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
星越华夏6 小时前
ESP32-CAM图像传输项目说明文档
java·后端·struts·esp32