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. 解决前端工程师与UI设计协同工作的问题

    前端工程师与UI设计协同工作主要环节在于设计图与前端界面是否一致.(还原度) 不得不说,设计图与前端界面实现不一致的问题时有发生.(好吧,我经验有限)所以经常写完的前端页面都需要去修改.(特别是做移动 ...

  2. day01_14.遍历数组

    <?php $a = array('a','b','c'); print_r($a); ?> 输出结果:Array ( [0] => a [1] => b [2] => ...

  3. Shape,expand_dims,slice基本用法

    import tensorflow as tf t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], ...

  4. Leetcode 427.建立四叉树

    建立四叉树 我们想要使用一棵四叉树来储存一个 N x N 的布尔值网络.网络中每一格的值只会是真或假.树的根结点代表整个网络.对于每个结点, 它将被分等成四个孩子结点直到这个区域内的值都是相同的. 每 ...

  5. Leetcode 419.甲板上的战舰

    甲板上的战舰 给定一个二维的甲板, 请计算其中有多少艘战舰. 战舰用 'X'表示,空位用 '.'表示. 你需要遵守以下规则: 给你一个有效的甲板,仅由战舰或者空位组成. 战舰只能水平或者垂直放置.换句 ...

  6. Nginx报 No input file specified. 的问题解决之路 转

    https://m.aliyun.com/yunqi/articles/34240 今天接手公司的一个项目,照例将项目clone下来,配置本地host,nginx,然后访问. 怎么回事?迅速在php的 ...

  7. Welcome-to-Swift-06函数(Functions)

    函数是执行特定任务的代码自包含块.给定一个函数名称标识, 当执行其任务时就可以用这个标识来进行"调用". Swift的统一的功能语法足够灵活来表达任何东西,无论是甚至没有参数名称的 ...

  8. 许式伟看 Facebook 发币(上): 区块链, 比特币与 Libra 币

    你好,我是七牛云许式伟. Facebook(脸书)于6月18日发布了其加密数字货币项目白皮书.该数字货币被命名为 Libra(天秤座),象征着平衡与公正.此前,BBC 报道说这个数字货币叫 Globa ...

  9. mybatis学习(十二)——mybatis逆向工程

    MyBatis Generator (MBG)是一个mabatis的代码生成器,能够根据表自动生成mapper接口,mapper.xml文件,javaBean文件. 1.MBG的下载 打开https: ...

  10. 基于Redis Sentinel的Redis集群(主从&Sharding)高可用方案

    本文主要介绍一种通过Jedis&Sentinel实现Redis集群高可用方案,该方案需要使用Jedis2.2.2及以上版本(强制),Redis2.8及以上版本(可选,Sentinel最早出现在 ...