本文主要是介绍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 = 0let r=arr.length-1while(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 falsehead = head.next;}return true}
module.exports = {isPail : isPail
};```
这篇关于javaScript -- 牛客NC96 判断一个链表是否为回文结构的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!