算法与数据结构
链表
链表的创建以及增删改查操作
function LinkedList() {var Node = function (element) {this.element = element;this.next = null;};var length = 0;var head = null;this.append = function (element) {var node = new Node(element), current;if (head === null) {head = node} else {current = headwhile (current.next) {current = current.next}current.next = node}length++};this.insert = function (position, element) {if (position >= 0 && position < length) {var node = new Node(element), current = head, prev, index = 0if (position === 0) {node.next = currenthead = node} else {while (index++ < position) {prev = currentcurrent = current.next}node.next = currentprev.next = node}length++return node} else {return false}};this.removeAt = function (position) {if (position > -1 && position < length) {var current = head, previous, index = 0if (position === 0) {head = current.next} else {while (index++ < position) {previous = currentcurrent = current.next}previous.next = current.nextlength--return current.element}} else {return null}};this.remove = function (element) {var index = this.indexOf(element)return this.removeAt(index)};this.indexOf = function (element) {var current = head, index = 0while (current) {if (element === current.element) {return index}index++current = current.next}return -1};this.isEmpty = function () {return length === 0};this.size = function () {return length};this.toString = function () {var current = head, string = ''while (current) {string += current.elementcurrent = current.next}return string};this.getHead = function () {return head}this.print = function () {return this.toString()};
}
let node = function(element) {this.element = elementthis.next = null
}
let linkedList = function() {this.head = new node('head')this.find = findthis.insert = insertthis.update = updatethis.remove = removethis.reverse = reverse
}
let find = function(item) {let currNode = this.headwhile (currNode.element !== item) {currNode = currNode.next}return currNode
}
let insert = function(newElement, item) {let newNode = new node(newElement)let currNode = this.find(item)newNode.next = currNode.nextcurrNode.next = newNode
}
let update = function(item, newItem) {let currNode = this.find(item)currNode.element = newItem
}
let remove = function(item) {let currNode = this.headwhile (currNode.next !== null && currNode.next.element !== item) {currNode = currNode.next}if (currNode.next !== null) {currNode.next = currNode.next.next}
}
let list = new linkedList()
list.insert('first', 'head')
list.insert('second', 'first')
list.insert('third', 'second')
console.log(list)
list.find('first')
console.log(list.find('first'))
list.update('third','three')
console.log(list)
list.remove('second')
console.log(list)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!