数据结构之链表结构
链表结构是无序的,可分为单链表和双链表这两种结构。
利用JS实现单链表:
function ListNode(item) {
this.item = item;
this.next = null;
}
function LinkedList() {
this.head = null;
this.length = 0;
}
LinkedList.prototype.append = function (item) {
const newNode = new ListNode(item);
if (this.length === 0) {
this.head = newNode;
} else {
// 找到最后一个元素,然后添加新元素
let current = this.head;
while (current.next) {
current = current.next
}
// 添加新元素
current.next = newNode;
}
this.length += 1
}
LinkedList.prototype.insert = function (position, item) {
if (position < 0) return false;
//
const newNode = new ListNode(item);
if(position === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
if (position > this.length) {
this.append(item);
} else {
//
let current = this.head;
let previous = null;
let index = 0;
while (index < position) {
//
previous = current;
current = current.next;
//
index++
}
//
previous.next = newNode;
newNode.next = current;
}
}
//
this.length += 1;
}
LinkedList.prototype.get = function (position) {
if (position < 0 || position >= this.length) return '该位置对应的数据为空'
//
let index = 0;
let current = this.head;
while (index < position) {
current = current.next;
index++
}
//
return current.item
}
LinkedList.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) return '该位置对应的数据为空';
//
if (position === 0) {
this.head = this.head.next
} else {
//
let current = this.head;
let previous = null;
let index = 0;
while (index < position) {
//
previous = current;
current = current.next;
//
index++;
}
//
previous.next = current.next;
}
//
this.length -= 1;
}
LinkedList.prototype.toString = function (params) {
console.log(this)
let current = this.head;
let result = '';
while (current) {
result += current.item + '-';
//
current = current.next
}
console.log(current)
return result;
}
利用JS实现双链表:
function ListNode(item) {
this.item = item;
this.prev = null;
this.next = null;
}
//
function DoublyLinkedList() {
//
this.head = null;
this.tail = null;
this.length = 0;
}
//
DoublyLinkedList.prototype.append = function (item) {
const newNode = new ListNode(item);
//
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode;
}
//
this.length += 1;
}
这里双链表只实现增加方法,其他的方法和单链表实现原理大同小异。相比于单链表而言,双链表增加了指向尾部变量以及每个节点增加了前指针(指向前一个元素),单链表只能单向遍历,双链表可以实现双向遍历,在某些时候可以利用二分法从后往前遍历,减少遍历时间。

浙公网安备 33010602011771号