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. Leetcode 464.我能赢吗

    我能赢吗 在 "100 game" 这个游戏中,两名玩家轮流选择从 1 到 10 的任意整数,累计整数和,先使得累计整数和达到 100 的玩家,即为胜者. 如果我们将游戏规则改为 ...

  2. HTTP重定向

    404 Not Found301 Moved Permanently302 Found500 Internal Server ErrorHTTP重定向就是通过301和302两种状态码来实现的. 302 ...

  3. 九度oj 1004

    题目1004:Median 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:17536 解决:4860 题目描述:                        Given an incre ...

  4. C++之Effective STL学习笔记Item14

    使用reserve来避免不必要的重新分配! The reserve member function allows you to minimize the number ofreallocations ...

  5. xampp下bugfree部署

    以Bugfree3.0.4为例,讲解如何搭建LAMP架构的Web服务器. Bugfree是一个XAMPP架构的网站,XAMPP(Apache+MySQL+PHP+PERL)是一个功能强大的搭建XAMP ...

  6. poj1324 Holedox Moving

    Holedox Moving Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 16980   Accepted: 4039 D ...

  7. bzoj3730 [震波][动态树分治+线段树+LCA]

    震波 Time Limit: 15 Sec  Memory Limit: 256 MBSubmit: 1573  Solved: 358[Submit][Status][Discuss] Descri ...

  8. 【前端学习笔记】2015-09-01 附二 关于jq选择器的简单运用

    根据id来选择------$("#id") 根据class来选择------$(".classname") 根据tag来选择-------$("tag ...

  9. 用户认证系统 django.contrib.auth模块

    一 导入auth模块 from django.contrib.auth.models import User from django.contrib import auth auth模块的操作针对的就 ...

  10. (超详细)使用git命令行将本地仓库代码上传到github或gitlab远程仓库

    (超详细)使用git命令行将本地仓库代码上传到github或gitlab远程仓库 本地创建了一个 xcode 工程项目,现通过 命令行 将该项目上传到 github 或者 gitlab 远程仓库,具体 ...