
[문제]
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
https://leetcode.com/problems/merge-two-sorted-lists/
/**
* 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) {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<ListNode> nodeList = new ArrayList<>();
int n1 = 0;
int n2 = 0;
while (true) {
if (list1 == null && list2 == null) {
break;
}
if (list1 != null) {
n1 = list1.val;
list1 = list1.next;
list.add(n1);
}
if (list2 != null) {
n2 = list2.val;
list2 = list2.next;
list.add(n2);
}
}
Collections.sort(list);
if (list.size() == 0) {
return null;
}
ListNode nowNode = new ListNode(list.get(0));
ListNode ans = nowNode;
for (int i = 1; i < list.size(); i++) {
ListNode nextNode = new ListNode(list.get(i));
nowNode.next = nextNode; // 연결
nowNode = nextNode;
}
return ans;
}
}
// 두 개의 정렬된 연결 리스트를 병합하여 하나의 정렬된 연결 리스트로 만들어라.
// 두 개의 리스트의 각각의 요소들을 순회하며 비교하 더 작은 녀석을 먼저 연결 리스트로 만들자.
// 1 1 2 3 4 4
//
두 개의 연결리스트를 순회하며 해당 value를 list에 모두 저장한 뒤 정렬하고, 이를 순회하며 연결리스트를 생성해주었다.
마지막으로 Head 노드를 return 해주면 된다.