The rubric "help a disabled person". We need a method to insert a new node in the middle of a single-linked list. Stuck at this stage (UPD: self-contained part of the code):
// превращает массив в список function arrayToList() { var number; var list = {number: number, next: list}; for (var i = arrayToList.arguments.length; i > -1; i--) { if (i < arrayToList.arguments.length - 1) list = {number: arrayToList.arguments[i], next: list}; else list = {number: arrayToList.arguments[i], next: null}; } return list; } var list = arrayToList(1,2,3,4,5,7,8,9,10,11,12); // должна вставлять 6 между 5 и 7, но не вставляет function insert(node, list) { if (list.number < node && list.next.number > node) // вставка в середину { var newnode = {number: node, next: list.next}; list.next = newnode; return list; } else if (list.number == node) // узел уже есть return "node " + node + " already exists in the list!"; else if (list.next != null) return insert(node, list.next); // собственно, источник проблемы else // вставка в конец { var newnode = {number: node, next: null}; list.next = newnode; return list; } } console.log(insert(6, list)); Everything works, but not so much: instead of the entire list, that part of it returns from the node that comes before the one that I am going to insert. Those. instead of node1 - node2 - ... - node (n-1) - node (n) - ... only node is returned (n-1) - node (n) - ... (where node (n) is the inserted node ). The point is a recursive call that every time starts a function with a short list. I understood the problem, but I did not find a solution ((Is the recursion justified at all? Maybe it can be a cycle somehow? Or somehow memorize the entire list from beginning to end? Need help.
function insert(node, list)is a function. How is she called? what is passed on to her. call example? - Grundy