js模拟链表
Posted muamaker
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js模拟链表相关的知识,希望对你有一定的参考价值。
链表: 每个元素,都有一个指针,指向下一个元素
//链表 var head = null; length = 0; class linkedList{ constructor(){ } append(ele){ var cnode = { ele:ele, next:null }; if(head === null){ head = cnode; }else{ //追加到节点 var current = head; while(current.next){ current = current.next; } current.next = cnode; } length++; } removeAt(pos){ //删除第几个元素 //检查越界 if(pos > -1 && pos < length){ var current = head, previous, index = 0; //移除第一项 if(pos == 0){ head = current.next; }else{ while(index++ < pos){ previous = current; current = current.next; } //前面的next,指向当前项的next,即干掉当前项 previous.next = current.next; } length--; return current.ele; }else{ return null; } } insert(pos,ele){ if(pos >= 0 && pos <= length){ var nodes = { ele:ele, next:null }; var current = head, previous, index = 0; if(pos == 0){ //第一项插入 nodes.next = current; head = nodes; }else{ while(index++ < pos){ previous = current; current = current.next; } nodes.next = current; previous.next = nodes; } length++; return true; }else{ return false; } } indexOf(ele){ var current = head; var index = -1; while(current){ if(current.ele === ele){ return index; } index++; current = current.next; } return index; } remove(ele){ var index = this.indexOf(ele); return this.removeAt(index); } toString(){ var current = head; var str = ‘‘; var index = 0; while(current){ str = str + current.ele+"-" + index + " "; index++; current = current.next; } console.log(str); } size(){ return length; } isEmpty(){ return !length; } getHead(){ return head; } } var list = new linkedList(); list.append("a"); list.append("b"); list.append("c"); list.insert(2,"bgb"); list.append("d"); list.toString();
以上是关于js模拟链表的主要内容,如果未能解决你的问题,请参考以下文章
[M链表] lc725. 分隔链表(模拟+代码优化+代码实现)
[M链表] lc725. 分隔链表(模拟+代码优化+代码实现)
[M链表] lc725. 分隔链表(模拟+代码优化+代码实现)