基础的数据结构可不要不会哦。
单向链表
//单向链表
function Node(val) {
this.val = val;
this.next = null;
}
function List(node) {
this.node = new Node(node);
//查找节点
this.find = function (target) {
let cur = this.node;
while (cur.val !== target) {
cur = cur.next;
if (!cur) {
return false
}
}
return cur
}
//插入节点
this.insert = function (node, target) {
let newNode = new Node(node);
let cur = this.find(target);
newNode.next = cur.next;
cur.next = newNode
}
//查找前一个节点
this.findPre = function (target) {
let cur = this.node;
while (!cur.next && cur.next.val !== target) {
cur = cur.next
}
return cur;
}
//删除节点
this.delete = function (target) {
let deleteNode = this.find(target);
this.findPre(deleteNode).next = deleteNode.next
}
}
//测试
let list = new List('pyx')
list.insert('wyt', 'pyx')
list.delete('pyx')
console.log(list.find('pyx'));
console.log(list.find('wyt'));
双向链表
//双向链表
function Node(val) {
this.val = val;
this.pre = null;
this.next = null
}
function List(node) {
this.node = new Node(node);
this.find = function (target) {
let cur = this.node;
while (cur.val !== target) {
cur = cur.next;
if (cur === null) {
return false
}
}
return cur
}
this.insert = function (node, target) {
let cur = this.find(target);
let newNode = new Node(node);
newNode.next = cur.next;
newNode.pre = cur;
// cur.next.pre = newNode;
cur.next = newNode
}
this.delete = function (target) {
let cur = this.find(target);
cur.pre.next = cur.next;
cur.next.pre = cur.pre;
}
}
let list = new List('pyx')
list.insert('wyt', 'pyx')
list.insert('wyt1', 'wyt')
list.delete('wyt')
console.log(list);
记录记录!