
-Code
/**
* 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 list1, ListNode list2) {
// 실제 결과의 포인터
ListNode answer = new ListNode();
// 현재 포인터
ListNode cur = answer;
// listNode 2개 모두 null인 경우 탈출
while (list1 != null || list2 != null) {
if (list1 == null) {
// list1이 null인 경우
cur.next = list2;
list2 = list2.next;
} else if (list2 == null) {
// list2이 null인 경우
cur.next = list1;
list1 = list1.next;
} else {
// 값의 크기 차이에 따른 다음 노드 추가
if (list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
}
// 다음 노드로 이동
cur = cur.next;
}
// 처음 시작 값으 0이므로 next를 통해 더미 데이터 넘김
return answer.next;
}
}
위와 같이 풀어서 해결했으나 이런 문제는 처음이라 첫 풀이 때
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode answer = new ListNode();
while (list1 != null || list2 != null) {
if (list1 == null) {
answer.next = list2;
list2 = list2.next;
} else if (list2 == null) {
answer.next = list1;
list1 = list1.next;
} else {
if (list1.val < list2.val) {
answer.next = list1;
list1 = list1.next;
} else {
answer.next = list2;
list2 = list2.next;
}
}
answer = answer.next;
}
return answer;
}
}
이렇게 했으나 틀렸습니다. 찾아보니 움직이는 포인터를 따로두고 반환 시에도 next로 한번 이동시켜서 해결하는 문제였습니다.
추가적으로
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode answer = new ListNode();
ListNode cur = answer;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
// 바로 노드 리스트 붙이기
cur.next = (list1 != null) ? list1 : list2;
return answer.next;
}
}
이렇게 바로 붙이는 방법도 있다는 것도 알게 되었습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [백준/Java] 2252번 줄 세우기 (0) | 2025.11.20 |
|---|---|
| [백준/Java] 34750번 추석은 언제나 좋아 (0) | 2025.11.20 |
| [LeetCode/Java] 20. Valid Parentheses (0) | 2025.11.19 |
| [백준/Java] 1717번 집합의 표현 (0) | 2025.11.19 |
| [백준/Java] 1707번 이분 그래프 (0) | 2025.11.19 |