leetcode Top100(23)回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 
输入:head = [1,2,2,1]
输出:true

采用动态数组,判断数组对称就可以了(这解法空间复杂度o(n))

package TOP21_30;

import Util.ListNode;

import java.util.ArrayList;
import java.util.List;

// 回文链表
//给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 输入:head = [1,2,2,1]
//输出:true
public class Top22 {
    public static boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }

        int length = list.size();

        int k = length / 2;
        for (int i = 0; i <= k; i++) {
            if (list.get(i) != list.get(length - 1 - i)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[] nums = {1,2,3,2,1};
        ListNode node =  ListNode.setNodes(0,nums);
        ListNode.printListData(node);

        int[] nums2 = {1,0,0};
        System.out.println(isPalindrome(ListNode.setNodes(0,nums2)));
    }
}

ListNode 类

package Util;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public static ListNode setNodes(int index,int[] nums){
        ListNode res = new ListNode();
        res.val = nums[index];
        if(index == nums.length-1){
            res.next = null;
            return res;
        }
        else{
            res.next = setNodes(index+1,nums);
        }
        return res;
    }

    public static void printListData(ListNode node){
        while (node!=null){
            System.out.println(node.val);
            node = node.next;
        }
    }
}

harryptter / LeetcodeTop100 · GitCode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值