/ * *
- [Header,next] – [data,next] -> [data,next] -> null;
* /
Simple is the basic function of the first single necklace table.
function ListNode(x) {
this.val = x;
this.next = null;
}
function LList() {
this.head = new ListNode("head");
this.insert = insert;
this.find = find;
this.findLast = findLast;
this.display = display;
this.remove = remove;
this.preNode = preNode;
}
// insert
function insert(oldnode, newVal) {
let otarget = this.find(oldnode);
// Compatible processing, if not passed where to insert, the default is directly inserted to the end
let newNode = new ListNode(newVal || oldnode);
if (otarget) {
newNode.next = otarget.next;
otarget.next = newNode;
}
else{
// Do not exist, insert directly in the tail
let getlast = this.findLast(); getlast.next = newNode; }}// findLast
function findLast(){
let curtent = this.head;
while (curtent) {
curtent = curtent.next;
if(! curtent.next)returncurtent; }}// find
function find(targetNode) {
let curtent = this.head;
while (curtent) {
if (curtent.val == targetNode) return curtent;
curtent = curtent.next;
}
return curtent;
}
// display
function display(){
let curent = this.head;
let res = [];
while(curent.next){
res.push(curent.next.val);
curent = curent.next;
}
console.log('=======display======',res);
}
// remove
// 1: query the current node first
// 2: does not query the current several values, directly to the previous node operation
function remove(rval){
// let exist = this.find(rval);
// if(exist){
// let preNode = this.preNode(rval);
// preNode.next = exist.next;
/ /}
let preNode = this.preNode(rval);
if( preNode.next ){ preNode.next = preNode.next.next; }}// get pre Node
function preNode(tnode){
let current = this.head;
while(current.next){
if(current.next.val == tnode) return current;
current = current.next;
}
return current;
}
var n = new LList();
n.insert("head".1);
n.insert(1.2);
n.insert(2.3);
n.insert(4);
n.insert(5);
n.display();
console.log(n);
/ / 2
n.remove(4);
n.remove(3);
n.remove(2);
n.display();
console.log(n);
Copy the code