Add linked_list.

This commit is contained in:
Oleksii Trekhleb
2018-03-25 23:28:32 +03:00
parent e9a3b9d30c
commit 83b3a35834
9 changed files with 2640 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
import { Node } from './Node';
export class LinkedList {
constructor() {
this.head = null;
}
append(value) {
const newNode = new Node(value);
// If there is no head yet let's make new node a head.
if (!this.head) {
this.head = newNode;
return newNode;
}
// Rewind to last node.
let currentNode = this.head;
while (currentNode.nextNode !== null) {
currentNode = currentNode.nextNode;
}
// Attach new node to the end of linked list.
currentNode.nextNode = newNode;
return newNode;
}
prepend(value) {
this.head = new Node(value, this.head);
}
deleteWithValue(value) {
}
render() {
let currentNode = this.head;
let index = 0;
while(currentNode.nextNode !== null) {
console.log(`Node #${index} data: ${currentNode.value}`);
currentNode = currentNode.nextNode;
index++;
}
// Print the tail.
console.log(`Node #${index} data: ${currentNode.value}`);
}
}

6
src/linked_list/Node.js Normal file
View File

@@ -0,0 +1,6 @@
export class Node {
constructor(value, nextNode = null) {
this.value = value;
this.nextNode = nextNode;
}
}

11
src/linked_list/index.js Normal file
View File

@@ -0,0 +1,11 @@
import { LinkedList } from "./LinkedList";
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
linkedList.append(3);
linkedList.prepend(4);
linkedList.prepend(5);
linkedList.render();