单链表
单链表封装
function LinkedList(){
function Node(data){
this.data = data;
this.next = null;
}
this.head = null;
this.length = 0;
}
向尾部添加
LinkedList.prototype.append = function(data) {
var newNode = new Node(data)
// 判断是否是第一个节点
if (this.length == 0) {
// 首节点为第一个加入的元素
this.head = newNode
}else {
var current = this.head
// 找到最后一个节点
while (current.next) {
current = current.next
}
// 最后一个节点指向新加入元素
current.next = newNode
}
this.length += 1
}
toString
LinkedList.prototype.toString = function() {
var current = this.head
let str = ''
while(current){
str += current.data
current = current.next
}
return str
}
添加到指定位置
LinkedList.prototype.insert = function(position,data) {
// 判断position越界
if (position < 0 || position > this.length) {
return false
}
var newNode = new Node(data)
var current = this.head
if (position == 0) {
newNode.next = this.head
this.head = newNode
} else {
var index = 0
var current = this.head
// 获取添加位置前的那个节点
var previous = null
while(index++ < position){
previous = current
current = current.next
}
newNode.next = current
previous.next = newNode
}
this.length += 1
}
获取对应位置的元素
LinkedList.prototype.get = function(position) {
if (position < 0 || position >= this.length) {
return
}
var current = this.head;
var index = 0;
while(current++ < position){
current = current.next;
}
return current.data;
}
返回元素在列表中的索引
LinkedList.prototype.indexOf = function(data) {
var current = this.head
var index = 0
while (current) {
// 判断数据是否相同
if (current.data == data) {
return index
}
// 向后遍历
current = current.next
index++
}
return -1
}
更新对应位置的元素
LinkedList.prototype.update = function(position,newData) {
if (position < 0 || position >= this.length) {
return
}
var current = this.head
var index = 0
while(current++ < position){
current = current.next
}
current.data = newData
}
移除特定位置
LinkedList.prototype.removeAt = function(position){
if (position < 0 || position >= this.length) {
return
}
if (position == 0) {
this.head = this.head.next
}else {
var index = 0
var current = this.head
var previous = null
while(index++ < position){
previous = current
current = current.next
}
previous.next = current.next
}
this.length -= 1
}
移除某项
LinkedList.prototype.remove = function(data){
var position = this.indexOf(data);
this.removeAt(position)
}