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
};```

猜你喜欢

转载自blog.csdn.net/sanjun_done/article/details/114698741
今日推荐