문제
제출한 코드
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
return getNextNode(l1, l2, new ListNode());
}
private ListNode getNextNode(ListNode l1, ListNode l2, ListNode currentNode) {
if (l1 == null && l2 == null) {
return null;
}
if (l1 == null) {
currentNode = new ListNode(l2.val, getNextNode(null, l2.next, currentNode));
} else if (l2 == null) {
currentNode = new ListNode(l1.val, getNextNode(l1.next, null, currentNode));
} else {
if (l1.val > l2.val) {
currentNode = new ListNode(l2.val, getNextNode(l1, l2.next, currentNode));
} else {
currentNode = new ListNode(l1.val, getNextNode(l1.next, l2, currentNode));
}
}
return currentNode;
}
}
잘한점
개선 할 점
- 문제 푸는데 시간이 너무 오래 걸림
- 무한 루프 ( while 문 )을 통해 풀려고 했는데, 정말 오래 오래 걸림
- 재귀함수를 통해 풀 수 있을것 같다는 생각을 정말 늦게 했음
- 재귀함수로 풀려고 시작을 했을 때에도 재귀함수가 끝나는 조건을 제대로 설정하지 못했음
- l1 / l2가 각각 널일때 경우를 제대로 생각해주지 못했음
- ListNode의 nextNode를 연결해주는것을 제대로 이해하지 못했음
