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
* print
*/ 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的更多相关文章

  1. [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 ...

  2. [Algorithom] Stack Data Structure in JavaScript

    A stack is a collection of items that obeys the principle of "last in, first out". Like a ...

  3. [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. ...

  4. [Algorithm] Heap data structure and heap sort algorithm

    Source, git Heap is a data structure that can fundamentally change the performance of fairly common ...

  5. [Algorithm] Trie data structure

    For example we have an array of words: [car, done, try, cat, trie, do] What is the best data structu ...

  6. HDU5739 Fantasia(点双连通分量 + Block Forest Data Structure)

    题目 Source http://acm.hdu.edu.cn/showproblem.php?pid=5739 Description Professor Zhang has an undirect ...

  7. hdu-5929 Basic Data Structure(双端队列+模拟)

    题目链接: Basic Data Structure Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 65536/65536 K (Ja ...

  8. CDOJ 483 Data Structure Problem DFS

    Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/proble ...

  9. HDU 5929 Basic Data Structure 【模拟】 (2016CCPC东北地区大学生程序设计竞赛)

    Basic Data Structure Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Oth ...

随机推荐

  1. 控制台窗口和powershell运行服务会卡住的解决办法

    之前使用nodejs做了一个简单的web服务,通过控制台窗口运行,通过浏览器访问发现有时候浏览器等很久数据都加载不出来,以为是代码有问题,后来发现是控制台卡住了,按一下enter键就好了,当时百度了一 ...

  2. [转] 查看 SELinux状态及关闭SELinux

    本文转载自: http://bguncle.blog.51cto.com/3184079/957315 查看SELinux状态: 1./usr/sbin/sestatus -v      ##如果SE ...

  3. html 标签附加文本属性

    <!DOCTYPE html> <html> <head> <script> function showDetails(animal) { var an ...

  4. Leetcode 454.四数相加II

    四数相加II 给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0. 为了使问题简单 ...

  5. Leetcode 448.找到所有数组中消失的数字

    找到所有数组中消失的数字 给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次. 找到所有在 [1, n] 范围之间没有出现 ...

  6. you build it,you run it

    this article is almostly about  a book named Migrating_to_Microservices_Databases, and it's just the ...

  7. 【转】C# 中的"yield"使用

    C# 中的"yield"使用 yield是C#为了简化遍历操作实现的语法糖,我们知道如果要要某个类型支持遍历就必须要实现系统接口IEnumerable,这个接口后续实现比较繁琐要写 ...

  8. Spring c3p0连接池通过Hibernate配置

    首先进行Hibernate配置,详见http://www.cnblogs.com/claricre/p/6509931.html 然后调用这三个包. 配置hibernate.cfg.xml文件: &l ...

  9. Linux Shell系列教程之(二)第一个Shell脚本

    本文是Linux Shell系列教程的第(二)篇,更多shell教程请看:Linux Shell系列教程 通过上一篇教程的学习,相信大家已经能够对shell建立起一个大体的印象了,接下来,我们通过一个 ...

  10. Java2WSDL 和 WSDL2Java(Axis)

    原文地址:https://www.ibm.com/developerworks/cn/webservices/ws-axisfaq/ 生成或取得WSDL文件 生成客户端或服务端代码 执行WSDL2Ja ...