SHARE
TWEET

Untitled

a guest Oct 15th, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Node {
  2.     constructor(data, next) {
  3.         this.data = data;
  4.         this.next = next;
  5.     }
  6. }
  7.  
  8. function createListFromArray(array) {
  9.     let list = null;
  10.     for (const item of array) {
  11.         list = new Node(item, list);
  12.     }
  13.     return list;
  14. }
  15.  
  16. function displayList(list) {
  17.     while (list) {
  18.         console.log(list.data);
  19.         list = list.next;
  20.     }
  21. }
  22.  
  23. function insertNth(head, index, data) {
  24.     if (index === 0) {
  25.         return new Node(data, head);
  26.     } else if (head && index > 0) {
  27.         head.next = insertNth(head.next, index - 1, data);
  28.         return head;
  29.     } else {
  30.         throw Error("Out of bounds exception");
  31.     }
  32. }
  33.  
  34. let array = [4,2,1];
  35. let list = createListFromArray(array);
  36. list = insertNth(list, 2, 3);
  37. displayList(list);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top