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

本文介绍如何利用Java实现链表回文结构的判断,通过中点反转和双指针法,简化链表操作,快速验证是否为回文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

描述
给定一个链表,请判断该链表是否为回文结构。
示例1
输入:
[1]
复制
返回值:
true
复制
示例2
输入:
[2,1]
复制
返回值:
false
复制
说明:
2->1
示例3
输入:
[1,2,2,1]
复制
返回值:
true
复制
说明:
1->2->2->1

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 == null){
            return false ;
        }
        if(head.next == null){
            return true ;
        }
        List<Integer> list = new ArrayList<Integer>();
        while(head != null){
            list.add(head.val) ;
            head = head.next ;
        }
        for(int i = 0 , j = list.size() -1 ; i < j ; i++ , j--){
            if(!list.get(i).equals(list.get(j)) ){
                return false ;
            }
        }
        return true ;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值