Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class LinkedListNode {
- constructor(value, next = null) {
- this.value = value;
- this.next = next;
- }
- }
- class LinkedList {
- constructor() {
- this.head = null;
- this.tail = null;
- this.el = [];
- }
- /**
- * Insert a new node to the head of linked list
- *
- * @param value Value of the new node
- * @returns {LinkedList}
- */
- prepend = function prepend(value) {
- let newNode = new LinkedListNode(value, this.head);
- this.head = newNode;
- console.log(this.head);
- if (!this.tail) {
- this.tail = newNode;
- }
- this.el.push(newNode);
- return this;
- };
- /**
- * Insert a new node to the tail of linked list
- *
- * @param value Value of the new node
- * @returns {LinkedList}
- */
- append = function append(value) {
- let newNode = new LinkedListNode(value);
- // If the linked list is empty
- if (!this.head) {
- this.head = newNode;
- this.el.push(newNode);
- this.tail = newNode;
- return this;
- }
- this.el.push(newNode);
- this.tail.next = newNode;
- this.tail = newNode;
- };
- /**
- * Delete a node at a given position
- *
- * @param position The position of the node to delete
- * @returns {null|*}
- */
- remove = function remove(position) {
- let current;
- // If the linked list is empty
- if (!this.head || position < 1) {
- return null;
- }
- // If we are deleting the head
- if (position === 1) {
- this.head = this.head.next;
- this.el.pop();
- return null;
- }
- current = this.head;
- // Traverse the linked list
- for (let i = 0; i < position - 2; i++) {
- current = current.next;
- }
- let target = current.next;
- current.next = target.next;
- // Empty the current
- return target;
- };
- /**
- * Reverse the linked list
- */
- reverse = function reverse() {
- let prevNode = null;
- let currentNode = this.head;
- let nextNode;
- while (currentNode) {
- // Store the next node into a variable
- nextNode = currentNode.next;
- // Change current link to the previous node
- currentNode.next = prevNode;
- // Move previous and current next to one position
- prevNode = currentNode;
- currentNode = nextNode;
- }
- this.tail = this.head;
- this.head = prevNode;
- };
- /**
- * Recursively reverse the linked list
- * @param headNode The head of the the linked list
- * @returns {*}
- */
- recursiveReverse = function recursiveReverse(headNode) {
- if (headNode === null || headNode.next === null) {
- return;
- }
- let recurReverse = this.recursiveReverse(headNode.next);
- headNode.next.next = headNode;
- headNode.next = null;
- return recurReverse;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement