문제링크: www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem
첫 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;
}
'알고리즘 > 해커랭크' 카테고리의 다른 글
[해커랭크] Insert a node at a specific position in a linked list (0) | 2021.01.13 |
---|---|
[해커랭크] Insert a node at the head of a linked list (0) | 2021.01.13 |
[해커랭크] Is This a Binary Search Tree? (0) | 2021.01.12 |
[해커랭크] Cycle Detection [JAVA] (0) | 2021.01.07 |
[해커랭크] Sparse Arrays [JAVA] (0) | 2021.01.07 |