javaScript -- 牛客NC96 判断一个链表是否为回文结构

题目描述
给定一个链表,请判断该链表是否为回文结构。
在这里插入图片描述

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head ListNode类 the head
 * @return bool布尔型
 */
function isPail( head ) {
    // write code hereNC
    //方法一:将链表转换为数组,用数组比较头尾是否一致
    let arr = [];
    while(head){
        arr.push(head.val);
        head  = head.next;
    }
    let l = 0
    let r=arr.length-1
    while(l<r){
        if(arr[l++]!==arr[r--]) return false
    }
    return true
}
module.exports = {
    isPail : isPail
};
/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head ListNode类 the head
 * @return bool布尔型
 */
function isPail( head ) {
    // write code hereNC
     //方法二:利用unshift()方法,得到倒叙的数据,再和之前的链表比较
    let per = head;
    let arr = [];
    while(per){
        arr.unshift(per.val);
        per = per.next;
    }
    while(head){
        if(head.val !== arr.pop()) return false
        head = head.next;
    }
    return true
   
}
module.exports = {
    isPail : isPail
};```

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值