Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- constructor(data, next) {
- this.data = data;
- this.next = next;
- }
- }
- function createListFromArray(array) {
- let list = null;
- for (const item of array) {
- list = new Node(item, list);
- }
- return list;
- }
- function displayList(list) {
- while (list) {
- console.log(list.data);
- list = list.next;
- }
- }
- function insertNth(head, index, data) {
- if (index === 0) {
- return new Node(data, head);
- } else if (head && index > 0) {
- head.next = insertNth(head.next, index - 1, data);
- return head;
- } else {
- throw Error("Out of bounds exception");
- }
- }
- let array = [4,2,1];
- let list = createListFromArray(array);
- list = insertNth(list, 2, 3);
- displayList(list);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement