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

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

相关推荐
GEEK零零七2 分钟前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
nightunderblackcat3 分钟前
新手向:实现ATM模拟系统
java·开发语言·spring boot·spring cloud·tomcat·maven·intellij-idea
Bug退退退1239 分钟前
RabbitMQ 高级特性之延迟队列
java·spring·rabbitmq·java-rabbitmq
先睡13 分钟前
RabbitMQ
java
笑衬人心。14 分钟前
Java 17 新特性笔记
java·开发语言·笔记
DoraBigHead1 小时前
小哆啦解题记——异位词界的社交网络
算法
麦兜*1 小时前
Spring Boot 企业级动态权限全栈深度解决方案,设计思路,代码分析
java·spring boot·后端·spring·spring cloud·性能优化·springcloud
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql