Skip to main content

设计链表

707. 设计链表

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val  和  next。val  是当前节点的值,next  是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性  prev  以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

示例

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2); //链表变为 1-> 2-> 3
linkedList.get(1); //返回 2
linkedList.deleteAtIndex(1); //现在链表是 1-> 3
linkedList.get(1); //返回 3

代码

class LinkNode {
constructor(val,next){
this.val = val
this.next = next || null
}
}

var MyLinkedList = function(val,next) {
this.head = null; // head节点
this.tail = null; // 尾节点
this.size = 0 // // 长度
};

/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
if (index < 0 || index >= this.size) return -1

let node = this.head
for(let i=0;i<index;i++){
node = node.next
}
return node
};

/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
let node = new LinkNode(val, this.head)
this.head = node
this.size++
// 没有尾结点,说明只有一个 node 节点,记录尾结点
if (!this.tail) this.tail = node
};

/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
const nextNode = new LinkNode(val)

if(!this.tail){
this.tail = nextNode
this.head = nextNode
}else{
// head 添加
this.tail.next = nextNode
// tail 添加
this.tail = nextNode
}
this.size++
};

/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
let node = this.head

if(index >= this.size){
this.addAtTail(val)
}else if(index <= 0){
this.addAtHead(val)
}else{
const current = this.get(index-1)

const nextNode = new LinkNode(val,node.next)
current.next = nextNode
}
this.size ++
};

/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
if (index < 0 || index >= this.size) return -1

const current = this.get(index-1)

if(index === 0){
this.head = this.head.next
}else{
current.next = current.next.next
}

// 处理尾节点
if(index === this.size-1){
this.tail = current
}

this.size --
};
const linkedList = new MyLinkedList();
linkedList.addAtHead(1);
// linkedList.addAtHead(2);
// linkedList.addAtHead(3);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2); //链表变为 1-> 2-> 3
console.log(linkedList.get(1)); //返回 2
linkedList.deleteAtIndex(1); //现在链表是 1-> 3
console.log(linkedList.get(1)); //返回 3

console.log('linkedList',linkedList)