본문 바로가기

알고리즘/해커랭크

[해커랭크] Inserting a Node Into a Sorted Doubly Linked List

문제링크: www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem

 

Inserting a Node Into a Sorted Doubly Linked List | HackerRank

Create a node with a given value and insert it into a sorted doubly-linked list

www.hackerrank.com

첫 if조건 밑의 코드만 작성했다가 테스트케이스 일부가 실패해서 예외가 될만한 상황들을 처리하는 로직을 갖다 붙였다. 그래서 이해하기 힘든 코드가 작성됐다


    // Complete the sortedInsert function below.

    /*
     * For your reference:
     *
     * DoublyLinkedListNode {
     *     int data;
     *     DoublyLinkedListNode next;
     *     DoublyLinkedListNode prev;
     * }
     *
     */
    static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data) {
        DoublyLinkedListNode newNode = new DoublyLinkedListNode(data);
        DoublyLinkedListNode searchKey = head;
        
        if(searchKey.next==null || searchKey.data > data){
            if(searchKey.data<data){
                searchKey.next = newNode;
                newNode.prev = searchKey;
                return head;
            }else{
                searchKey.prev = newNode;
                newNode.next = searchKey;
                return newNode;
            }
        }
        
        while(searchKey.next !=null && searchKey.next.data <= data){
            searchKey = searchKey.next;
        }

        newNode.next = searchKey.next;
        if(searchKey.next!=null){
            searchKey.next.prev = newNode;
        }
        searchKey.next = newNode;
        newNode.prev = searchKey;
        
        return head;

    }