mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add linked_list.
This commit is contained in:
51
src/linked_list/LinkedList.js
Normal file
51
src/linked_list/LinkedList.js
Normal 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
6
src/linked_list/Node.js
Normal 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
11
src/linked_list/index.js
Normal 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();
|
||||
Reference in New Issue
Block a user