|
| 1 | +/** |
| 2 | + * Definition for singly-linked list. |
| 3 | + * function ListNode(val, next) { |
| 4 | + * this.val = (val===undefined ? 0 : val) |
| 5 | + * this.next = (next===undefined ? null : next) |
| 6 | + * } |
| 7 | + */ |
| 8 | +class ListNode { |
| 9 | + constructor(val, next) { |
| 10 | + this.val = (val === undefined ? 0 : val); |
| 11 | + this.next = (next === undefined ? null : next); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {ListNode} list1 |
| 17 | + * @param {ListNode} list2 |
| 18 | + * @return {ListNode} |
| 19 | + */ |
| 20 | +var mergeTwoLists = function (list1, list2) { |
| 21 | + if (null === list1) return list2; |
| 22 | + if (null === list2) return list1; |
| 23 | + |
| 24 | + // dummy & head |
| 25 | + let dummy = new ListNode(), head = dummy; |
| 26 | + |
| 27 | + // go thru the linked list if either is null, update it a to b |
| 28 | + while (list1 && list2) { |
| 29 | + // console.log(`--> list`) |
| 30 | + // console.log("-> list1") |
| 31 | + // console.log(list1) |
| 32 | + // console.log("-> list2") |
| 33 | + // console.log(list2) |
| 34 | + console.log("--> dummy") |
| 35 | + console.log(dummy) |
| 36 | + console.log(`----> A:${list1.val}, B:${list2.val}`) |
| 37 | + // asc => check min |
| 38 | + if (list1.val <= list2.val) { |
| 39 | + // dummy.next = new ListNode(list1.val); |
| 40 | + dummy.next = list1; |
| 41 | + list1 = list1.next; |
| 42 | + // console.log("New list1") |
| 43 | + // console.log(list1) |
| 44 | + } else { |
| 45 | + // dummy.next = new ListNode(list2.val); |
| 46 | + dummy.next = list2; |
| 47 | + list2 = list2.next; |
| 48 | + // console.log("New list2") |
| 49 | + // console.log(list2) |
| 50 | + } |
| 51 | + |
| 52 | + // NOTE: THISISS!!!!!!!! |
| 53 | + dummy = dummy.next; |
| 54 | + |
| 55 | + // carry on the while if needed |
| 56 | + dummy.next = (null === list1) ? list2 : list1; |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | + console.log("head") |
| 61 | + console.log(head.next) |
| 62 | + |
| 63 | + return head.next; |
| 64 | +}; |
| 65 | +mergeTwoLists(new ListNode(1, new ListNode(2, new ListNode(4))), new ListNode(1, new ListNode(3, new ListNode(4)))) |
0 commit comments