【注释详细,思路清晰】【打卡第17天】leetcode热题HOT100之Java实现:234. 回文链表

1、题目描述

请判断一个链表是否为回文链表。

 2、题目分析

什么是回文链表?

 示例1不是回文链表,[1,2],并不对称

 示例2是回文链表,[1,2,2,1],是整个集合是对称的。

 3、代码实现

整个代码实现也非常简单。

一部分是将链表中的值存储到集合List中。

另一部分判断List集合中的首尾元素是否相等。

/**
 * 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; }
 * }
 */
 /**
    定义一个List集合存储链表中的结点,只需要判断收尾位置的结点,是否对称值是否相等
  */
class Solution {
    public boolean isPalindrome(ListNode head) {
        //定义List集合存储链表元素
        List<Integer> list = new ArrayList<>();
        while(head != null){
            list.add(head.val);
            head = head.next;
        }
        
        // 判断List是否对称
        // List集合的元素首位置
        int startIndex = 0;
        // List集合的尾元素位置
        int endIndex = list.size() - 1;
        while(startIndex < endIndex){
            if(! list.get(startIndex).equals(list.get(endIndex))){
                return false;
            }
            startIndex++;
            endIndex--;
        }
        return true;
    }
}

加油!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值