设计链表的实现。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。
在链表类中实现这些功能:
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
整体实现:
相关代码:
// 初始化数据结构
var MyLinkedList = function () {
this.head = null
this.rear = null
this.len = 0
};
function ListNode(val) {
this.val = val
this.next = null
}
// 获取index位置节点的值
MyLinkedList.prototype.get = function (index) {
if (index < 0 || index > this.len - 1) {
return -1
}
var node = this.head
while (index-- > 0) {
if (node.next == null) {
return -1
}
node = node.next
}
return node.val
};
// 在链表头部添加节点
MyLinkedList.prototype.addAtHead = function (val) {
var node = new ListNode(val) //每次添加都创建一个节点
if (this.head == null) {
this.rear = node
} else {
node.next = this.head
}
this.head = node
this.len++
};
//在链表尾部添加节点
MyLinkedList.prototype.addAtTail = function (val) {
var node = new ListNode(val)
if (this.head == null) {
this.head = node
} else {
this.rear.next = node
}
this.rear = node
this.len++
};
// 在指定位置之前插入节点
MyLinkedList.prototype.addAtIndex = function (index, val) {
if (index <= 0) {
return this.addAtHead(val)
}
if (this.len < index) {
return
}
if (index == this.len) {
return this.addAtTail(val)
}
var node = this.head
while (index-- > 1) { //遍历链表
node = node.next
}
var newnode = new ListNode(val)
newnode.next = node.next
node.next = newnode
this.len++
};
// 删除指定位置index的节点
MyLinkedList.prototype.deleteAtIndex = function (index) {
if (index < 0 || index > this.len - 1 || this.len == 0) {
return
}
if (index == 0) {
this.head = this.head.next
this.len--
return
}
var node = this.head
var myindex = index;
while (index-- > 1) { //遍历链表
node = node.next
}
if (myindex == (this.len - 1)) {
this.rear = node
}
node.next = node.next.next
this.len--
};
运行相关代码:
var obj = new MyLinkedList()
obj.addAtHead(2)
obj.addAtTail(3)
obj.addAtIndex(0, 1)
var param_1 = obj.get(1)
console.log(param_1)
obj.deleteAtIndex(1)
console.log(obj)
结果如下:
MyLinkedList {
head: ListNode { val: 1, next: ListNode { val: 3, next: null } },
rear: ListNode { val: 3, next: null },
len: 2
}