본문 바로가기
Programming/DataStructure

[자료구조] sorting the element of the doubly linked list (feat.for loop)

by soccerman 2020. 2. 25.
반응형

참고자료

https://www.javatpoint.com/program-to-sort-the-elements-of-the-doubly-linked-list

 

Program to Sort the Elements of the Doubly Linked List - javatpoint

Program to Sort the Elements of the Doubly Linked List on fibonacci, factorial, prime, armstrong, swap, reverse, search, sort, stack, queue, array, linkedlist, tree, graph etc.

www.javatpoint.com

Data structure를 공부하며 node를 swap하는 것에 익숙해진 상황이었다.

그래서인지 Doubly linked list의 원소들을 오름차순으로 sort하는 알고리즘을 짤 때도 data를 변경하는 방식이 아닌 node를 swap하는 방식으로 시도했다.

이것은 나의 실수이다. 코드가 훨씬 복잡해지기 때문이다.

 

Doubly Linked List

위와 같이 각 노드가 previous, next pointer로 연결된 Doulby linked list가 있다고 하면,

 

1. node를 swap하여 sort하게 되면

아래와 같이 각 node의 previous와 next pointer를 수정하고,  각 노드가 head 혹은 tail 인 경우 이를 수정해야 한다.

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
void sort(){
    struct node *current = head;
    struct node *cur_temp = NULL;
    int temp = 0;
    
    if(head==NULL){
        return;
    }
    
    while(current->next!=NULL){
        cur_temp=current->next;
        while(cur_temp!=NULL){
            if(current->data > cur_temp->data){
                current->next = cur_tmep->next;
                cur_tmep->next = current->next;
                cur_tmep->previous = current->previous;
                current->previous = cur_tmep->previous;
                //exception
                if(current==head){
                    head==cur_temp;
                }
                if(cur_temp==tail){
                    tail=current;
                }
            }
            cur_temp=cur_temp->next;
        }
        current=current->next;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

2. data를 변경하여 sort하게 되면

int temp에 노드의 데이터값을 저장하고 두 노드의 data값을 바꿔주는 방식이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void sort(){
    struct node *current = head;
    struct node *cur_temp = NULL;
    int temp = 0;
    
    if(head==NULL){
        return;
    }
    
    while(current->next!=NULL){
        cur_temp=current->next;
        while(cur_temp!=NULL){
            if(current->data > cur_temp->data){
            temp = current->data;
            current->data = cur_temp->data;
            cur_temp->data = temp;
            }
            cur_temp=cur_temp->next;
        }
        current=current->next;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

data만 변경해주는 식으로 하게 되면, 해당 노드의 head, tail 여부를 따지지 않아도 되고, pointer를 변경하는 방식보다 논리구조가 간단하므로 오류발생의 여지가 적다.

얻고자 하는 결과에 따라 유연하게 생각하여 간단한 논리구조로 알고리즘을 짜는 것이 중요한 것 같다.

 

Plus.

For Loop 심화

나는 Doubly Linked list에서 모든 노드의 값을 비교하는 과정에서 while문을 이용하여 아래와 같이 코드를 짰다.

 

1
2
3
4
5
6
7
8
9
10
11
12
while(current->next!=NULL){
        cur_temp=current->next;
        while(cur_temp!=NULL){
            if(current->data > cur_temp->data){
            temp = current->data;
            current->data = cur_temp->data;
            cur_temp->data = temp;
            }
            cur_temp=cur_temp->next;
        }
        current=current->next;
    }
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

여기서 for문을 이용하면 아래와 같이 코드를 조금 짧게 작성할 수 있다.(원문의 코드를 참고하였음)

 

1
2
3
4
5
6
7
8
9
 for(current = head; current->next != NULL; current = current->next) {  
            for(cur_temp = current->next; cur_temp != NULL; cur_temp = cur_temp->next) {  
                if(current->data > cur_temp->data) {  
                    temp = current->data;  
                    current->data = cur_temp->data;  
                   cur_temp->data = temp;  
                }  
            }  
        }  
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

for(첫 loop때 사용되는 변수 선언 ; 조건 ; loop마다 업데이트되는 사항)

{

loop

}

 

for문의 구성요소가 위와 같다고 하면, 기존의 while문에서 loop마다 업데이트 되는 사항을 for문 초기화부분에 포함시킬 수 있다.

현재 알고리즘에 적용하면 cur_temp = cur_temp->next, current=current->next부분이 for문 초기화부분에 들어가게 된다.

 

while 문으로 하나 for문으로 하나 구조의 복잡성부분에서는 차이가 없는 것 같다. 코드를 짧게 할 수 있다는 점과 다양한 코드를 이해하는 시야를 키운다는 면에서 이 부분을 기억하고 가면 좋을 것 같아 기록에 남긴다.

 

 

 

 

반응형

댓글