Skip to content

Instantly share code, notes, and snippets.

@jacintoface
Created March 3, 2018 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacintoface/0d20106b58d0a59ee6c269fc4d37f29e to your computer and use it in GitHub Desktop.
Save jacintoface/0d20106b58d0a59ee6c269fc4d37f29e to your computer and use it in GitHub Desktop.
js实现一个单向链表
function LinkedList () {
function Node (node) {
this.node = node
this.next = null
}
let length = 0
let head = null
this.append = function (node) {
var target = new Node(node)
var current
if (head === null) {
head = target
} else {
current = head
while (current.next) {
current = current.next
}
current.next = target
length++
}
}
this.insert = function (element, position) {
if (position >= 0 && position < length) {
let node = new Node(element)
let current = head
let previous
let index
if (position === 0) {
node.next = current
head = node
} else {
while (index < position) {
previous = current
current = current.next
index++
}
previous.next = node
node.next = current
length++
return true
}
}else {
return false
}
}
this.removeAt = function (pos) {
if (pos > -1 && pos < length) {
var current = head
var previous
var index = 0
if (pos === 0) {
head = current.next
} else {
while (index < pos) {
previous = current
current = current.next
index++
}
previous.next = current.next
}
length--
return current.node
}
}
this.remove = function (element) {
let index = this.indexOf(element)
return this.removeAt(index)
}
this.indexOf = function (element) {
let current = head
let index = 0
while (current) {
if (current.node === element) {
return index
}
index++
current = current.next
}
return -1
}
this.isEmpty = function () {
return length === 0
}
this.size = function () {
return length
}
this.getHead = function () {
return head
}
this.toString = function () {
var current = head
var string = ''
while (current) {
string += current.node.toString() + (current.next ? '\r\n' : "")
current = current.next
}
return string
}
this.print = function () {
}
}
var link = new LinkedList()
link.append(12)
link.append(14)
link.append(15)
link.append(17)
console.log(link.indexOf(17))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment