我已经用JavaScript编写了以下函数,以检查单个链表是否是回文。但是,我10个测试中有2个失败了,我不知道为什么。
这是我要参加的测试。
对于回文,两者都应返回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.pop()而不是使用arr.shift()。这将使第一个元素脱离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;
}