[LeetCode] 6.Merge Two SortedLists

2020. 12. 30. 17:33

leetcode.com/problems/merge-two-sorted-lists/

 

Merge Two Sorted Lists - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. Problem

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

 

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4]

 

Example 2:

Input: l1 = [], l2 = [] Output: []

 

Example 3:

Input: l1 = [], l2 = [0] Output: [0]

 

2. code

package leetCode;

import java.util.ArrayList;

public class MergeTwoSortedLists {

	public static void main(String[] args) {
		ListNode resultNode = new ListNode();
		//[1,2,4]
		ListNode node1 = new ListNode(4);
		ListNode node2 = new ListNode(2, node1);
		ListNode node3 = new ListNode(1, node2);

		//[1,3,4]
		ListNode nodeA = new ListNode(4);
		ListNode nodeB = new ListNode(3, nodeA);
		ListNode nodeC = new ListNode(1, nodeB); 

		resultNode = mergeTwoLists(node3, nodeC);
	}
	
	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		ListNode result = null;	
		while(l1 != null || l2 != null) {
			if(l1 == null) {
				result = makeNewNode(result, l2.val);
				l2 = l2.next;
			} else if(l2 == null) {
				result = makeNewNode(result, l1.val);
				l1 = l1.next;
			} else if(l1.val <= l2.val) {
				result = makeNewNode(result, l1.val);
				l1 = l1.next;
			} else {
				result = makeNewNode(result, l2.val);
				l2 = l2.next;
			}
		}
		return result;
    }
	
	public static ListNode makeNewNode(ListNode result, int val) {
		ListNode n = new ListNode(val);
		if(result == null) {
			result = n;
		} else {
			ListNode head = result;
			while(head.next != null) {
				head = head.next;
			}
			head.next = new ListNode(val);
		}
		return result;
	}
}

3. Report

여러번 시행착오를 겪고... 겨우 나왔는데 속도가 느리다

개선해보자..

'Algorithm > 문제' 카테고리의 다른 글

[LeetCode] 8.Remove Element  (0) 2021.01.04
[LeetCode] 7.Longest Common Prefix  (0) 2020.12.30
[LeetCode] 5.Palindrome Number  (0) 2020.12.29
[LeetCode] 4.Reverse Integer  (0) 2020.12.28
[LeetCode] 3.Roman to Integer  (0) 2020.12.28

BELATED ARTICLES

more