본문으로 바로가기

www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=linked-lists

 

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

문제를 요약하자면, 정렬된 이중연결리스트에 입력 데이터를 추가하는 것이다. 대신 입력 데이터를 추가할 때 정렬이 깨지지 않도록 적절한 position에 추가해야 한다.

 

내가 생각한 풀이 방식은, 연결리스트를 순환하면서 입력 데이터보다 큰 노드를 찾아 새로운 노드를 추가하면 된다.

연결리스트 개념을 알고 있다면 생각보다 간단한 문제라고 할 수 있다~

 

내가 푼 코드

 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    static class DoublyLinkedListNode {
        public int data;
        public DoublyLinkedListNode next;
        public DoublyLinkedListNode prev;

        public DoublyLinkedListNode(int nodeData) {
            this.data = nodeData;
            this.next = null;
            this.prev = null;
        }
    }

    static class DoublyLinkedList {
        public DoublyLinkedListNode head;
        public DoublyLinkedListNode tail;

        public DoublyLinkedList() {
            this.head = null;
            this.tail = null;
        }

        public void insertNode(int nodeData) {
            DoublyLinkedListNode node = new DoublyLinkedListNode(nodeData);

            if (this.head == null) {
                this.head = node;
            } else {
                this.tail.next = node;
                node.prev = this.tail;
            }

            this.tail = node;
        }
    }

    public static void printDoublyLinkedList(DoublyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException {
        while (node != null) {
            bufferedWriter.write(String.valueOf(node.data));

            node = node.next;

            if (node != null) {
                bufferedWriter.write(sep);
            }
        }
    }

    // Complete the sortedInsert function below.

    /*
     * For your reference:
     *
     * DoublyLinkedListNode {
     *     int data;
     *     DoublyLinkedListNode next;
     *     DoublyLinkedListNode prev;
     * }
     *
     */
    static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data) {
        // 연결리스트를 순환할 tmp node
        DoublyLinkedListNode tmp = head;
        
        // head node의 값이 입력 데이터보다 클 경우
        if (tmp.data > data) {
            DoublyLinkedListNode newNode = new DoublyLinkedListNode(data);
            
            newNode.next = tmp;
            tmp.prev = newNode;
            head = newNode;
            
            return head;
        }
        
        while (tmp != null) {
            DoublyLinkedListNode newNode = new DoublyLinkedListNode(data);
            
            // 현재 node의 데이터가 입력값보다 클 경우
            if (tmp.data > data) {
                newNode.next = tmp;
                tmp.prev.next = newNode;
                newNode.prev = tmp.prev;
                tmp.prev = newNode;
                
                break;
            }
            
            // 현재 node가 마지막 노드일 경우
            if (tmp.next == null) {
                tmp.next = newNode;
                newNode.prev = tmp;
                break;
            }
            
            tmp = tmp.next;
        }
        
        return head;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int t = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int tItr = 0; tItr < t; tItr++) {
            DoublyLinkedList llist = new DoublyLinkedList();

            int llistCount = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int i = 0; i < llistCount; i++) {
                int llistItem = scanner.nextInt();
                scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

                llist.insertNode(llistItem);
            }

            int data = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            DoublyLinkedListNode llist1 = sortedInsert(llist.head, data);

            printDoublyLinkedList(llist1, " ", bufferedWriter);
            bufferedWriter.newLine();
        }

        bufferedWriter.close();

        scanner.close();
    }
}