[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 get
s 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 get
s in a linked list an operation that takes O(n)
time.
While get
s 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 ...
随机推荐
- 理一理Spring如何对接JUnit
测试代码 package org.simonme.srcstudy.spring3.demo.stub; import static org.junit.Assert.assertNotNull; i ...
- Selenium WebDriver-通过ActionChains实现页面元素拖拽
#encoding=utf-8 import unittest import time import chardet from selenium import webdriver class Visi ...
- 2章 perl标量变量
标量变量 单单存储一个值得变量 ,单个标量值 $name 为变量 区分大小写 $barney=$barney*2 第一次 取值 等号右边 :第二次 赋值 等号左边 双目操作符 ...
- 《如何成为一位大家愿意追随的Leader》读后感
今天看了左耳朵耗子老师的文章<如何成为一位大家愿意追随的Leader>深有感触.每一行字都往心里说,文章里说到Leader和Boss的不同点在于,Leader是大家跟我一起上,而Boss则 ...
- FZOJ Problem 2107 Hua Rong Dao
...
- SharepPoint 2013安装体会
SharePoint 2013出来了,一直没有找到合适的机器来安装.前天腾出来一台内存8G的机器,决定在Hyper-V上安装在一台虚机,然后装个Windows 2012,再装SharePoint 20 ...
- POJ3928 Ping pong
Time Limit: 1000MS Memory Limit: 65536KB 64bit IO Format: %lld & %llu Description N(3<= ...
- net4:GridView中的重要操作(添加checkbox,以及鼠标动作,行颜色等)
原文发布时间为:2008-07-29 -- 来源于本人的百度文章 [由搬家工具导入] using System;using System.Data;using System.Configuration ...
- 转 Python常见数据结构整理
http://www.cnblogs.com/jeffwongishandsome/archive/2012/08/05/2623660.html Python常见数据结构整理 Python中常见的数 ...
- upper_bound()和lower_bound()
ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, la ...