(一)题目
设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
(二)思路
- 实现单链表
- 在单链表的操作中,添加prev字段
- 处理头结点,尾节点等特殊判断
(三)代码实现
var MyLinkedList = function() {
this.head=null
this.length=0
};
/** 获取链表中第 index 个节点的值。如果索引无效,则返回-1。
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
if(index < 0 || index >= this.length){
return -1
}
let cur=this.head;
let sum=0;
if(index == 0){
return cur.val
}else{
while(sum<index){
cur=cur.next;
sum++
}
return cur.val
}
};
/** 在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
//头节点不存在
if(!this.head){
this.head={prev:null,val,next:null}
}else{
//头节点存在
let node={prev:null,val,next:this.head}
this.head=node
}
this.length++
};
/** 将值为 val 的节点追加到链表的最后一个元素。
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
let node={prev:null,val,next:null}
//头节点不存在
if(!this.head){
this.head=node
}else{
//找到倒数第二个节点
let cur=this.head
while(cur.next){
cur=cur.next
}
cur.next=node
node.prev=cur
}
this.length++
};
/** 在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
//超过长度就return
if (index < 0 || index > this.length){
return
}
let node = { prev:null, val, next: null };
let cur = this.head,
pre,
sum = 0;
if (index === 0) {
return this.addAtHead(val); //index为0, 头部插入
} else if (index === this.length) {
return this.addAtTail(val); //index = length,在末尾进行追加
} else {
while (sum <= index - 1) {
//找到index位置的前一个节点
pre = cur;
cur = cur.next; //下一个节点
sum++;
}
pre.next = node;
node.prev = pre;
node.next = cur;
cur.prev = node
}
this.length++
};
/** 如果索引 index 有效,则删除链表中的第 index 个节点。
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
if (index < 0 || index >= this.length) return;
let cur = this.head,
pre,
countIndex = 0;
if (index === 0){
this.head = cur.next
cur.prev = null
}else{
while (countIndex++ < index) {
//找到删除位置的前一个节点
pre = cur;
cur = cur.next;
}
if (cur) {
//直接链接到删除位置的下一个节点
pre.next = cur.next;
cur.prev = pre.next;
} else {
pre.next = null;
}
}
this.length--
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/
参考链接
作者:力扣 (LeetCode) 链接:leetcode.cn/leetbook/re…
写在最后的话
学习路上,常常会懈怠
《有想学技术需要监督的同学嘛~》 mp.weixin.qq.com/s/FyuddlwRY…