
문제 링크
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
let result = new ListNode()
let change = result
while (l1 !== null && l2 !== null) {
if (l1.val <= l2.val) {
change.next = l1
l1 = l1.next
} else {
change.next = l2
l2 = l2.next
}
change = change.next
}
if (l1 !== null) { change.next = l1 }
if (l2 !== null) { change.next = l2 }
return result.next
};
새로운 노드 리스트(result)를 만들어준 뒤 변수(change)에 할당해준다.
두 리스트를 비교하며 미리 만들어 놓은 변수(change)에 넣어준다.
주소를 참조하고 있는 result.next를 return
let result = new ListNode()
let change = result
위의 과정을 통해 현재 result와 change는 같은 주소를 바라보고 있으므로
change가 변경되면 result도 변경된다.
change.next = l1
change.next = l2
change = change.next
이후 이런 과정을 통해 change가 참조하고 있는 주소 값은 변경되지만 result가 참조하고 있는 주소 값은 변경되지 않으므로 result를 return 하게 된다.
또한 리스트를 생성하는 시점에서 result.val이 0으로 초기화되기 때문에 result.next를 return 시킨다.