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;
}

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

相关推荐
1000世界小札1 小时前
《大话数据结构》第9章精读:归并排序与快速排序完整 C++ 实现
数据结构·c++·算法
2601_956121974 小时前
背包基础篇(01、完全、分组、多重、混合)
c++·算法·动态规划
Java牛马4 小时前
SpringBoot Starter 依赖相关总结
java·spring·springboot·starter·自动装配·依赖
吴声子夜歌4 小时前
Java面试——Spring Cloud原理及应用(二)
java·spring cloud·面试
东小西5 小时前
【SAA实战】第 1 篇:ReactAgent 入门——先撸个"会调工具的助手"跑起来
java·人工智能·spring
兴通物联科技5 小时前
SMT PCB 微小 DataMatrix 码扫不动问题分析 兴通 XT8601B 600 万像素工业读码器落地实践
大数据·人工智能·单片机·嵌入式硬件·算法·计算机视觉
mqiqe6 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
脉动数据行情6 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股
月华路8 小时前
G1 GC 对数组与大对象(Humongous)的处理
java·jvm·算法