总结
- 书写题目的时候,需要先声明链表,再声明节点。
- 并且
length是在你每次进行操作的时候,才++,不需要声明一个函数来遍历
- 调用声明在
prototype上的方法的时候,需要使用this.方法名来调用。
- ⚠️链表为空情况
- 插入到
index位置的元素,倒着判断时(找上一个元素),需要注意,如果是在index = 0插入,就又回到了在链表首部插入的解法
index--的位置,应该在每次判断当前index是否符合之后,再--
- 要仔细检查,自己书写的
h.next会不会出错,是否不会涉及到null
代码
var MyLinkedList = function() {
this.head = null;
this.tail = null;
this.length = 0;
};
var listNode = function(val) {
this.val = val
this.next = null
}
MyLinkedList.prototype.get = function(index) {
let h = this.head;
if (!h || index < 0 || index > this.length) {
return -1;
}
while (h) {
if (index == 0) {
return h.val;
}
index--;
h = h.next;
}
return -1;
};
MyLinkedList.prototype.addAtHead = function(val) {
let node = new listNode(val);
node.next = this.head;
this.head = node;
this.length++;
};
MyLinkedList.prototype.addAtTail = function(val) {
let node = new listNode(val);
let h = this.head;
if (!h) {
this.head = node;
this.length++;
}else {
while (h.next != null) {
h = h.next;
}
h.next = node;
node.next = null;
this.length++;
}
};
MyLinkedList.prototype.addAtIndex = function(index, val) {
let node = new listNode(val);
if (index <= 0) {
this.addAtHead(val);
}else {
if (index == this.length) {
this.addAtTail(val);
} else if (index < this.length) {
let h = this.head;
while (h != null) {
if (index == 1) {
node.next = h.next;
h.next = node;
this.length++;
break;
}
index--;
h = h.next;
}
}
}
};
MyLinkedList.prototype.deleteAtIndex = function(index) {
if (index >= 0 && index < this.length) {
let tempt = null;
let h = this.head;
if (index == 0) {
this.head = this.head.next;
}
while (h != null) {
if (index == 1) {
tempt = h.next;
h.next = h.next.next;
tempt.next = null;
this.length--;
break;
}
index--;
h = h.next;
}
}
};
附录