BM13 判断一个链表是否为回文结构

题目连接:BM13 判定链表是否回文结构

判定链表是否回文结构


题目描述

在这里插入图片描述


思路

由于链表是随机存储结构,若想要比较头部尾部的数据,首先转换为List集合形式。


步骤

  • 首先定义一个List列表集合。
  • 遍历链表元素,并把数值转移到list集合中。
  • 在list集合中查找比较头尾的数值,判定链表是否回文结构。
  • 代码如下:
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        if (head.next == null) {
            return true;
        }
        List<Integer> nums = new ArrayList<>();
        //链表转换为list
        while (head != null) {
            nums.add(head.val);
            head = head.next;
        }
        int i = 0;
        int j = nums.size() - 1;
        while (i < j) {
            //不等于则返回null
            if (!nums.get(i).equals(nums.get(j))) {
                return false;
            }
            ++i;
            --j;
        }
        return true;
    }
}

运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值