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

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

相关推荐
l1t13 分钟前
测试DuckDB v2.1.0-alpha49002的bignum乘法
数据库·sql·算法·duckdb
譕痕14 分钟前
stripe 实例
java·开发语言·stripe·checksession
Nil20821 分钟前
LeetCode 283移动零
数据结构·算法·leetcode
墨子夕22 分钟前
设计模式——Java × Python 双语言精讲 · 23 个经典模式 + 现代演进(前言篇)
java·开发语言·设计模式
骇客野人27 分钟前
Linux 全套实操方案(含目录详解、文件传输、日志、文件规范、环境变量、Java 应用部署运维)
java·linux·运维
CQU_JIAKE32 分钟前
10.18【A】
算法
.Bryce.1 小时前
MCP+A2A+ANP,Agent通信协议的完整知识地图
java·人工智能·后端·agent·通信协议
SL_staff1 小时前
规则引擎选型陷阱:为什么QPS不是JVS-Rules对比Drools的核心指标
java·开源·全栈
LMT流氓兔1 小时前
第五单元——第4课:给工具参数加校验
java·前端·算法·ai·langchain
eleven_4u1 小时前
RocketMQ相关问题
java·运维·中间件