什么是链表?链表是一种物理存储结构上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中指针链接次序实现的,这里就不展示图片了简单说一下
index.html
script 引入link.js
<script >
let link = new LinkNode()
link.push(1)
link.push(2)
link.push(3)
function decToBinary(num) {
const s = new Stack()
while(num > 0) {
s.push(num % 2)
num = Math.floor(num / 2)
}
let str = ''
while(s.len() > 0) {
str += s.pop()
}
return str
}
</script >
link.js
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
class LinkNode{
constructor() {
this.head = null
this.count = 0
}
push(data) {
let node = new Node(data)
if(!this.head) {
this.head = node
} else {
let current = this.head
while(current.next) {
current = current.next
}
current.next = node
}
this.count++
}
get(index) {
if(index >= this.count) {
return undefined
} else {
let current = this.head
for(let i =0; i< index; i++) {
current = current.next
}
return current.data
}
}
set(index, data) {
if(index >= this.count) {
return false
} else {
let current = this.head
for(let i =0; i< index; i++) {
current = current.next
}
current.data = data
return true
}
}
remove(index) {
if(index >= this.count) {
return false
} else {
let current = this.head
let previous = null
for(let i =0; i< index; i++) {
previous = current
current = current.next
}
previous.next = current.next
this.count--
}
}
insert(index, data) {
if(index>=this.count){
return false
}else{
let node = new Node(data)
let current = this.head
let previous = null
for(let i =0;i<index;i++){
previous = current
current = current.next
}
previous.next = node
node.next = current
this.count++
return true
}
}
}