JS实现双向链表
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();
最后
以上就是激动乐曲最近收集整理的关于前端企业面试题:企业真实案例——25的全部内容,更多相关前端企业面试题内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复