javascript - 在 JavaScript 中检查链表是否为回文
问题描述
我在 JavaScript 中编写了以下函数来检查单链表是否是回文。但是,我在 10 次测试中有 2 次失败,我不知道为什么。
这是我正在下降的测试。
- l: [0, 1, 0]
- l: [1, 1000000000, -1000000000, -1000000000, 1000000000, 1]
对于回文,两者都应该返回 true,但我的函数返回 false。
这是我的代码:
function isListPalindrome(l) {
let curr = l;
let arr = [];
if (l == null)
return true;
// push all elements of l into the stack.
// a stack in JS is an array.
while(curr != null){
arr.push(l.value);
// move ahead:
curr = curr.next;
}
let curr2 = l;
// Traverse the list again & check by popping from the stack:
while(curr2 != null){
// get the top most element on the stack:
let num = arr.shift();
// check if the node data isn't the same as the element popped:
if (curr2.value != num){
return false;
}
// move ahead:
curr2 = curr2.next;
}
return true;
}
谢谢!
解决方案
在第一个 while 循环中,您正在推动l.value但l没有递增,因此它将相同的值推送到arr。
你现在有arr,它应该是l反向的。在第二个 while 循环中,而不是使用arr.shift()使用arr.pop()。这将从arr堆栈中取出第一个元素。请记住,堆栈是先进后出的。
另请注意,当您从前到后比较列表时,您将到达一个不相关的点,即中间点。一旦您知道正向列表中的一半值与反向列表中的值相同,您就知道其余的将通过测试。
这就是它的样子。你应该试着弄清楚如何自己做赔率。
function isListPalindrome(l) {
let curr = l;
let arr = [];
if (l == null)
return true;
// push all elements of l into the stack.
// a stack in JS is an array.
while(curr != null){
arr.push(curr.value);
// move ahead:
curr = curr.next;
}
let curr2 = l;
let length = arr.length;
// Traverse the list again & check by popping from the stack:
while(curr2 != null){
// get the top most element on the stack:
let lastNum = arr.pop();
// check if the node data isn't the same as the element popped:
if (curr2.value != lastNum){
return false;
}
// Half way point for evens
if (length / 2 === arr.length) {
return true;
}
// move ahead:
curr2 = curr2.next;
}
return true;
}
推荐阅读
- python - ModuleNotFoundError:没有名为“xxxx.yyy”的模块
- python - 我收到 selenium Webdriver 的错误
- reactjs - 如何在 React 中获取自定义下拉菜单的选定值
- python - 递归字典的工作问题
- reactjs - 如何在 React 的同一选项卡中监听本地存储的变化?
- android - java.lang.NoSuchMethodError:没有静态方法元工厂
- android - setExpedited 是如何工作的,它和前台服务一样好和可靠吗?
- python - 如何向 Keras 模型添加输出间约束
- docker - 无法在 gitlab runner 中连接 docker 容器
- sql-server - 如何在 MS SQL 中将 NULL 日期编码为空白