본문 바로가기
Programming/Data Structure

[Hackerrank] MergeTwoSortedLinkedLists

by 읽고 쓰는 개발자 2020. 12. 2.

https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/problem

Merge two sorted linked lists | HackerRank

Given the heads of two sorted linked lists, change their links to get a single, sorted linked list.

www.hackerrank.com

package exam.complete;

//https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/problem

import exam.SinglyLinkedListNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MergeTwoSortedLinkedLists {
    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
        List<Integer> list = new ArrayList<>();

        while (head1 != null) {
            list.add(head1.data);
            head1 = head1.next;
        }
        while (head2 != null) {
            list.add(head2.data);
            head2 = head2.next;
        }
        Collections.sort(list);

        SinglyLinkedListNode returnNode = new SinglyLinkedListNode(list.get(0));
        SinglyLinkedListNode nodeForLoop = returnNode;
        for (int i = 1; i < list.size(); i++) {
            SinglyLinkedListNode node = new SinglyLinkedListNode(list.get(i));
            nodeForLoop.next = node;
            nodeForLoop = nodeForLoop.next;
        }


        return returnNode;
    }

}

'Programming > Data Structure' 카테고리의 다른 글

[Hackerrank] ReverseADoublyLinkedList  (0) 2020.12.02
[Hackerrank] PrintLinkedList  (0) 2020.12.02
[Hackerrank] MatchingStrings  (0) 2020.12.02
[Hackerrank] InsertNodeAtTail  (0) 2020.12.02
[Hackerrank] InsertNodeAtPosition  (0) 2020.12.02