[Algorithm] Linked List Data Structure in JavaScript
A linked list is a collection of items where each item points to the next one in the list. Because of this structure, linked lists are very slow when searching for an item at a particular index. An array, by comparison, has quick gets when searching for an index, but a linked list must start at the beginning, often called the "head", and loop through each item's next property until we arrive at the item. This makes gets in a linked list an operation that takes O(n) time.
While gets might be slow in a linked list, it's other operations, like push and delete come with some great benefits we will see in the lesson.
/**
* Linked list
*
* API:
* push
* pop
* get
* delete
* isEmpty
*/ function createNode(value) {
return {
value,
next: null
}
} function createLinkedList() {
return {
head: null,
tail: null,
length: 0,
push(value) {
/**Key takeaway:
* Assign new node to current tail's next value
* Then
* Reassign the tail to new node
*/
// Create Node
const node = createNode(value); // If this is the first one
if (this.head === null) {
this.head = node
this.tail = node
this.length++;
return node;
} // if there already has nodes
this.tail.next = node;
this.tail = node;
this.length++;
return node;
},
pop() {
const node = this.tail;
// if this is no node
if (!this.head) {
return null;
} // if there is one node
if (this.head === this.tail) {
this.head = null;
this.tail = null;
return node;
} let current = this.head;
let penultimate = null; while (current) {
const {next} = current;
if (next && next == this.tail) {
penultimate = current;
break;
}
current = current.next;
}
penultimate.next = null;
this.tail = penultimate;
this.length--;
return node;
},
get(index = 0) {
// no node in the list, return null
if (!this.head) {
return null;
} // if the index < 0 or > length - 1, out of range
if (index < 0 || index > this.length - 1) {
return null;
} // if index = 0, then return the first
if (index === 0) {
return this.head;
} let current = this.head;
let i = 0;
while (i < index) {
i++;
current = current.next;
} return current;
},
delete(index = 0) {
/**
* Key takewawy:
* If we delete tail, we need to reassign the tail
*/
// no node in the list, return null
if (!this.head) {
return null;
} // if the index < 0 or > length - 1, out of range
if (index < 0 || index > this.length - 1) {
return null;
} // if index = 0, then return the first
if (index === 0) {
const node = this.head;
this.head = node.next;
this.length--;
return node;
} let i = 0;
let current = this.head;
let previous = null; while (i < index) {
i++;
previous = current;
current = current.next;
} const deleted = current;
previous.next = deleted.next; // If we delete the tail, we need to reassign tail
if (previous.next === null) {
this.tail = previous;
} this.length--;
return deleted;
},
isEmpty() {
return this.length === 0;
},
print() {
/**Key takeway:
* remember to assign next node to current
* Move the while loop
* */
let nodes = []; if (!this.head) {
return 'Empty list';
} let current = this.head;
while (current) {
nodes.push(current.value);
current = current.next;
} return nodes.join(' => ');
}
};
} module.exports = {createLinkedList}
test:
const {createLinkedList} = require('../src/linked-list');
describe('linked list', () => {
test('push: should add node into array', () => {
const l = createLinkedList();
// linked list should be empty
expect(l.isEmpty()).toBe(true);
// push a new node
l.push('a');
expect(l.isEmpty()).toBe(false);
expect(l.length).toEqual(1);
expect(l.print()).toEqual('a');
// push a second node
l.push('b');
expect(l.length).toEqual(2);
expect(l.print()).toEqual('a => b');
});
test('pop: should remove the last node from the list', () => {
const l = createLinkedList();
l.push('a');
l.push('b');
l.push('c');
expect(l.length).toEqual(3);
const p = l.pop();
expect(p.value).toEqual('c');
expect(l.length).toEqual(2);
});
test('get: should return the node for the given index', () => {
const l = createLinkedList();
// empty list, return null
expect(l.get(0)).toBeNull();
l.push('a');
l.push('b');
l.push('c');
expect(l.length).toEqual(3);
// out of index, retur null
expect(l.get(-1)).toBeNull();
expect(l.get(4)).toBeNull();
// return the head
expect(l.get(0).value).toEqual('a');
// index in range not head
expect(l.get(2).value).toEqual('c');
});
test('delete: should delete the node from the given index', () => {
const l = createLinkedList();
// empty list, return null
expect(l.delete(0)).toBeNull();
l.push('a');
l.push('b');
l.push('c');
expect(l.length).toEqual(3);
// out of index, retur null
expect(l.delete(-1)).toBeNull();
expect(l.delete(4)).toBeNull();
// return the head
expect(l.delete(0).value).toEqual('a');
expect(l.length).toEqual(2);
// delete the tail, reassign the tail
expect(l.delete(1).value).toEqual('c');
expect(l.tail.value).toEqual('b');
});
});
[Algorithm] Linked List Data Structure in JavaScript的更多相关文章
- [Algorithms] Tree Data Structure in JavaScript
In a tree, nodes have a single parent node and may have many children nodes. They never have more th ...
- [Algorithom] Stack Data Structure in JavaScript
A stack is a collection of items that obeys the principle of "last in, first out". Like a ...
- [Algorithm] JavaScript Graph Data Structure
A graph is a data structure comprised of a set of nodes, also known as vertices, and a set of edges. ...
- [Algorithm] Heap data structure and heap sort algorithm
Source, git Heap is a data structure that can fundamentally change the performance of fairly common ...
- [Algorithm] Trie data structure
For example we have an array of words: [car, done, try, cat, trie, do] What is the best data structu ...
- HDU5739 Fantasia(点双连通分量 + Block Forest Data Structure)
题目 Source http://acm.hdu.edu.cn/showproblem.php?pid=5739 Description Professor Zhang has an undirect ...
- hdu-5929 Basic Data Structure(双端队列+模拟)
题目链接: Basic Data Structure Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 65536/65536 K (Ja ...
- CDOJ 483 Data Structure Problem DFS
Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/proble ...
- HDU 5929 Basic Data Structure 【模拟】 (2016CCPC东北地区大学生程序设计竞赛)
Basic Data Structure Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Oth ...
随机推荐
- acdsee 15中文版的许可证密钥+激活方法
按以下方法就可以使用了,进入注册表的命令是:开始-运行-输入regedit 进入注册表后按下面的步骤操作就行. ACDSee15中文版激活英文版激活码5NR9CW-SSRMMY-KFWMQU-ZP ...
- python 学习分享-列表元组篇
1 列表(list) 下面的代码就是把一个变量赋值为列表 a=['laay','aay','ay','y'] 列表中存在索引,可以通过索引来访问列表中的值,也可以通过索引完成切片 print(a[0] ...
- jquery拼接字符串
1. $("#div").append("<table><tr align='center'>" +"<td >& ...
- 装箱I(01背包)
描述 给两个有一定容量的箱子,往里面装宝石(宝石总容量不能超过箱子容量),不同的宝石有不同的容量和价值.求两个箱子里最大宝石的价值. 输入 line 1: Input n; n:表示宝石数量 ...
- 将json的文本文件转换为csv文件
import pandas as pd import fire import glob import json def text_to_csv(file_name): json_data = json ...
- iis上的反向代理
阅读文章: IIS上的反向代理 ARR(Application Request Routing)
- Hibernate框架简述(转)
转自:http://www.cnblogs.com/eflylab/archive/2007/01/09/615338.html Hibernate的核心组件在基于MVC设计模式的JAVA WEB应用 ...
- 天气预报接口:SmartWeather API中key的计算方法
这个代码大家都蛮感兴趣,我在git开源了一个用于收集天气信息的系统,基于python语言的,请大家参考: https://github.com/BerlinSun/WeatherForecast -- ...
- ACM程序设计选修课——1076汇编语言(重定向+模拟)
1076: 汇编语言 Time Limit: 1 Sec Memory Limit: 128 MB Submit: 34 Solved: 4 [Submit][Status][Web Board] ...
- [luoguP2754] 星际转移问题(最大流)
传送门 不同的时间每个飞船所在的地点不同,给我们启示按照时间构建分层图. 同一个地点 x <x, dayi - 1> -> <x, dayi> 连一条容量为 INF 的边 ...