<알고리즘 문제풀이&연습>/[C++] 백준, 프로그래머스 등등

[C 자료구조] Linked Lists - Inserting a Node Into a Sorted Doubly Linked List

BlockDMask 2017. 6. 29. 19:53
반응형

0) 제목

  • Hackerrank 의 Linked Lists 부분의 Inserting a Node Into a Sorted Doubly Linked List 문제입니다.

  • C언어를 이용하여 풀었습니다.

1) 문제설명

  • Doubly Linked List 에서 데이터를 오름차순으로 넣는 문제입니다.

  • 데이터와 Linked Lists의 헤드가 파라미터로 주어집니다.

  • 주어진 파라미터를 이용해서 적절한 위치에 새 노드를 삽입하는 문제입니다.

2) 풀이과정

  • 새 노드를 동적할당을 이용하여 만들고, 현재 노드가 empty리스트 인지 검사 후 

  • 새 노드가 들어갈 적절한 위치를 찾아주었습니다.

  • 찾은 위치가 맨 앞일때, 맨 뒤일때, 가운데 일때를 구분하여서 구현했습니다.


3) 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
   typedef struct _Node
   {
     int data;
     struct _Node *next;
     struct _Node *prev;
   } Node;
*/
 
Node* SortedInsert(Node *head,int data)
{
    Node * newNode = (Node *)malloc(sizeof(Node));
    Node * curNode = head;
    
    newNode->data = data;
    newNode->next = NULL;
    newNode->prev = NULL;
    
    //empty List.
    if(curNode==NULL){
        head = newNode;
        return head;
    }
    
    //check the right node or stop at right node.
    while((curNode->data < data) && (curNode->next != NULL)){
        curNode = curNode->next;
    }       
    
    //insert the next of last node.
    if(curNode->next == NULL && curNode->data < data){
        curNode->next = newNode;
        newNode->prev = curNode;
        return head;
    }
    
    //insert front.
    if(curNode->prev == NULL){
        head = newNode;
    }else{
    //insert mid.
        curNode->prev->next = newNode;   
    }
    
    newNode->prev = curNode->prev;
    newNode->next = curNode;
    curNode->prev = newNode;
    
    return head;
}
cs


주석 내부에 있는 부분은 C언어 문법에 맞게 고쳤습니다.

(Hackerrank 에서는 C++ 문법으로 지원)

경로 : Dashboard>Data Structures>Linked Lists>Inserting a Node Into a Sorted Doubly Linked List

출처 : [HackerRank] https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list

반응형