LeetCode hot100-24

234. 回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为
回文链表
。如果是,返回 true ;否则,返回 false

这题又写得和官方解法1一模一样了,就是空间复杂度为O(n)。如果想要空间复杂度为O(1)的话,官方解法3 是把后半部分链表翻转,然后两个指针分别往前后比较每个数。完了再把后半部分链表翻转回来。额,为了节省空间复杂度解法上有点复杂啊。就不贴这种解法了。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {

        List<Integer> list = new ArrayList<Integer>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int i = 0, j = list.size() - 1;
        while (i < j) {
            if (list.get(i) != list.get(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;

    }
}

相关推荐

  1. LeetCodehot100

    2024-04-11 11:48:05       57 阅读
  2. 一个月速刷leetcodeHOT100 day02

    2024-04-11 11:48:05       37 阅读
  3. 一个月速刷leetcodeHOT100 day 01

    2024-04-11 11:48:05       94 阅读
  4. 一个月速刷leetcodeHOT100 day03

    2024-04-11 11:48:05       33 阅读
  5. 一个月速刷leetcodeHOT100 day08 两道DP题 一道子串

    2024-04-11 11:48:05       35 阅读
  6. LeetCode hot100-24

    2024-04-11 11:48:05       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-11 11:48:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-11 11:48:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-11 11:48:05       82 阅读
  4. Python语言-面向对象

    2024-04-11 11:48:05       91 阅读

热门阅读

  1. Day10:学习尚上优选项目

    2024-04-11 11:48:05       28 阅读
  2. c++和R语言数据类型的比较

    2024-04-11 11:48:05       34 阅读
  3. docker重启错误-重启命令一直卡住

    2024-04-11 11:48:05       36 阅读
  4. Linux命令学习—linux 的常用命令

    2024-04-11 11:48:05       29 阅读
  5. Ajax

    Ajax

    2024-04-11 11:48:05      31 阅读