链表是一种线性结构,通过引用字段将分离的元素连接在一起。
链表的实现
let MyList = function(){
this.head = undefined;
this.size = 0;
}
MyList.prototype.addHead = function(val){
if(!this.head) this.head = {val:val,next:null};
else{
let node = {val:val,next:null};
node.next = this.head;
this.head = node;
}
this.size ++;
}
MyList.prototype.getByIndex = function(index){
if(this.size == 0 || index >= this.size) return -1;
let pre = this.head;
let count = 0;
while(pre){
if(count == index) return pre.val;
pre = pre.next;
count ++;
}
}
MyList.prototype.addTail = function(val){
if(this.size == 0) this.head = {val,next:null};
else{
let pre = this.head;
while(pre.next){
pre = pre.next;
}
pre.next = {val,next:null};
}
this.size++;
}
MyList.prototype.addAtIndex = function(index,val){
if(index == 0){
this.addHead(val);
}else if(index == this.size){
this.addTail(val);
}else if(index < 0) return;
else{
let pre = this.head;
let count = 1;
while(pre){
if(index == count){
let node = {val,next:null};
node.next = pre.next;
pre.next = node;
this.size++;
return;
}
pre = pre.next;
count++;
}
}
}
MyList.prototype.deleteAtIndex = function(index){
if(index <0 || index >= this.size) return;
else if(index == 0){
this.head = this.head.next;
this.size --;
}else if(this.size == index - 1){
let pre = this.head;
let count = 1;
while(pre){
if(count == this.size - 1){
pre.next = null;
this.size --;
return;
}
pre = pre.next;
count ++;
}
}else{
let pre = this.head;
let count = 1;
while(pre){
if(count == index - 1){
pre.next = pre.next.next;
this.size --;
return;
}
pre = pre.next;
count ++;
}
}
}
let list = new MyList();
list.addHead("first");
list.addHead("second");