您的位置:首页 > Web前端

前端企业面试题:企业真实案例——25

2020-09-07 13:30 806 查看
JS实现双向链表
[code]class Node {
constructor(value){
this.val = value;
this.next = null;
this.prev = null;
}
}

class DoubleLinkList {
constructor(){
//记录头和尾
this.head = this.tail = null;
}
find(value) {  //查找某个元素
var currentNode = this.head;
while (currentNode.val != value) {
if (currentNode.next == null) {
return 'error';
}
currentNode = currentNode.next;
}
return currentNode;
}
push(value) { //像末尾添加
var node = new Node(value);
if(this.head == null){
this.head = node;
this.tail = node;
}
this.tail.next = node;
node.prev = this.tail;
this.tail = node;
}
pop(){ ... } //从末尾删除
insertBefore(target, value){ ... } //插入到某个节点前面
insertAfter(target, value) { ... } //插入到某个节点后面
remove(value) { //删除某个节点
var node = this.find(value);
//如果是头结点
if(node == this.head){
this.head = node.next;
this.head.prev = null;
}
//如果是尾节点
if(node == this.tail){
this.tail = this.tail.prev;
this.tail.next = null;
}
//如果是中间
node.prev.next = node.next;
node.next.prev = node.prev;
}
display() { //打印所有节点
var head = this.head
do {
console.log(head.element)
head = head.next
} while (head != null)
}
lastNode() { //获取最后一个节点
return this.tail;
}
firstNode() { ... } //获取第一个节点
}

var list = new DoubleLinkList();
list.push("aa");
list.push("bb");
list.push("cc");
list.display();

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: