# JS数据结构与算法--单向链表

2018/07/13 10:28

1.append方法，向链表末尾插入一个节点

2.insert(position,element)，向指定位置插入一个节点

3.removeAt(position)移除某个位置上的节点

``````"use strict";

class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
/**
* 单向链表
*/
constructor() {
this.length = 0;
}

append(element) {
let node = new Node(element),
current;
if (this.getHead() === null) {  //判断链表是否为空
}
else {
while (current.next) { //最后一项的next=null
current = current.next;
}
current.next = node;
}

this.length++;
}

insert(position, element) {
if (position >= 0 && position <= this.size()) {   //检查边界
let node = new Node(element),
index = 0,
previous;
if (position === 0) {   //插入第一项
node.next = current;
}
else {
while (index++ < position) {
previous = current;
current = current.next;

}
node.next = current;
previous.next = node;
}

this.length++;
return true;
}
else {
return false;
}
}

removeAt(position) {
if (position >= 0 && position <= this.length) {
let current = this.head,
index = 0,
previous;
if (position === 0) {
}
else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length--;
return current.element;
}
else {
return null;
}
}

indexOf(element) {
let current = this.getHead(), index=0;
while (current) {
if(current.element===element){
return index;
}
index++;
current = current.next;
}
return -1;
}

remove(element) {
let position = this.indexOf(element);
return this.removeAt(position);
}

}

isEmpty() {
return this.length === 0;
}

size() {
return this.length;
}

toString() {

let current = this.getHead(),
string = '';

while (current) {
string += current.element + (current.next ? ', ' : '');
current = current.next;
}
return string;

}

print() {
console.log(this.toString());
}
}``````

0
0 收藏

0 评论
0 收藏
0