I got this problem from LeetCode
question 21,https://leetcode.com/problems/merge-two-sorted-lists/
but it's not only to solve this question
here is my description of my problem I have a original linked list [1,2,4],it's data structure is like :
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
I want to insert 3 after 2, and make it to [1,2,3,4].
almost from all the tutorials I've read ,they tell me to do like this:
var insert = function(l1) {
let i=0;
let p = l1;
while(i<1 && p){
p = p.next;
i++;
}
let tem = new ListNode(3,p.next);
p.next = tem;
return p;
};
but the p is [2,3,4] because p is already assign to be [2,4] when finish the while loop ,obviously this is not right .
so how can I fix this?
and why the tutorials say like
find the node(p) you want to insert after,and create a new node(q), and q.next = p.next ;p.next = q?
whileloop after the first iteration? You're not even testing at which node in the list you're currently.