版权声明:任先阳 任 先 阳 任先 先阳,nvcc.cc、www.nvcc.cc、sbfox.com、www.sbfox.com https://blog.csdn.net/qq_39571197/article/details/85232163
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回文字符串 - 双向链表</title>
</head>
<body>
<script>
class Node{
constructor(value = null, prev = null, next = null) {
this.value = value;
this.next = next;
this.prev = prev;
}
}
class List{
constructor() {
this.head = new Node();
}
push(value) {
let lastNode = this.head;
while (lastNode.next) {
lastNode = lastNode.next;
}
lastNode.next = new Node(value, lastNode);
}
}
const list = new List();
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(3);
list.push(2);
list.push(1);
console.log(isPalindrome(list));
function isPalindrome(list) {
//寻找终点
let lastNode = list.head;
while (lastNode.next) {
lastNode = lastNode.next;
}
let firstNode = list.head;
while (firstNode.next) {
firstNode = firstNode.next;
if (firstNode.value !== lastNode.value) return false;
lastNode = lastNode.prev;
}
return true;
}
</script>
</body>
</html>