UNPKG

@sivarajans/linked-list

Version:

Linked list implementation in javascript

1 lines 2.43 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports["default"]=exports.LinkedListNode=void 0;function _defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var LinkedListNode=function LinkedListNode(data,next){_classCallCheck(this,LinkedListNode),this.data=data,this.next=next};exports.LinkedListNode=LinkedListNode;var LinkedList=function(){function LinkedList(){_classCallCheck(this,LinkedList),this.head=null,this.tail=null,this.size=0}return _createClass(LinkedList,[{key:"add",value:function add(data){var newNode=new LinkedListNode(data,null);null==this.head?(this.head=newNode,this.tail=newNode):(this.tail.next=newNode,this.tail=newNode),this.size++}},{key:"remove",value:function remove(node){for(var current=this.head,prev=null;current;){if(current===node)return null==prev?this.head=current.next:prev.next=current.next,null==current.next&&(prev.next=null,this.tail=prev),this.size--,!0;prev=current,current=current.next}return!1}},{key:"indexOf",value:function indexOf(node){for(var index=-1,current=this.head;current;){if(current===node)return++index;current=current.next,index++}return-1}},{key:"addFirst",value:function addFirst(data){if(0==this.size)this.add(data);else{var newNode=new LinkedListNode(data,this.head);this.head=newNode,this.size++}}},{key:"addAtIndex",value:function addAtIndex(data,index){this.isValidIndex(index),0==index&&this.addFirst(data);for(var leftNode=this.head;1<index;)leftNode=leftNode.next,index--;leftNode.next=new LinkedListNode(data,leftNode.next),this.size++}},{key:"removeAtIndex",value:function removeAtIndex(index){this.isValidIndex(index);for(var toRemove=this.head;0<index;)toRemove=toRemove.next,index--;this.remove(toRemove)}},{key:"isValidIndex",value:function isValidIndex(index){if(0>index||index>=this.size)throw new Error("invalid index")}}]),LinkedList}();exports["default"]=LinkedList;