The underlying data structure should not fail.
Singly linked list
// one-way linked list
function Node(val) {
this.val = val;
this.next = null;
}
function List(node) {
this.node = new Node(node);
// Find the node
this.find = function (target) {
let cur = this.node;
while(cur.val ! == target) { cur = cur.next;if(! cur) {return false}}return cur
}
// Insert the node
this.insert = function (node, target) {
let newNode = new Node(node);
let cur = this.find(target);
newNode.next = cur.next;
cur.next = newNode
}
// Find the previous node
this.findPre = function (target) {
let cur = this.node;
while(! cur.next && cur.next.val ! == target) { cur = cur.next }return cur;
}
// Delete a node
this.delete = function (target) {
let deleteNode = this.find(target);
this.findPre(deleteNode).next = deleteNode.next
}
}
/ / test
let list = new List('pyx')
list.insert('wyt'.'pyx')
list.delete('pyx')
console.log(list.find('pyx'));
console.log(list.find('wyt'));
Copy the code
Two-way linked list
// Two-way linked list
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);
Copy the code