设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
在链表类中实现这些功能:
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。 addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。 addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。 addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。 deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
this.hair= new Node(-1,null, null);
this.tail = new Node(1, null, this.hair)
this.hair.next = this.tail
this.size = 0
};
class Node{
constructor(val, next,pre){
this.val =val;
this.pre =pre;
this.next =next;
}
insertBefore(val){
const node = new Node(val, this,this.pre);
this.pre && (this.pre.next = node);
this.pre = node ;
}
pushBack(val){
const node = new Node(val, this.next,this);
this.next &&(this.next.pre = node);
this.next = node
}
ease(){
/* 这里必须有pre next 用虚拟头尾节点来保证*/
this.pre.next = this.next
this.next.pre = this.pre
}
}
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
if(index< 0 || index >this.size-1)return -1 ;
let res = this.hair ;
while(index> -1){
index--
res = res.next
}
return res.val
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
this.hair.pushBack(val) ;
this.size++
return this.hair.next
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
this.tail.insertBefore(val)
this.size++
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
if( index >this.size)return -1 ;
if(index <= -1){ index =0}
let res = this.hair ;
while(index> -1){
index--
res = res.next
}
res.insertBefore(val)
this.size++
};
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
if(index < 0 | index > this.size -1){ return false}
let res = this.hair
while(index > -1){
index--
res = res.next
}
res.ease()
this.size--
};