Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어로 이중 연결 리스트(Doubly Linked List)의 임의 위치에 노드 삽입하기

연결 리스트란?

연결 리스트(Linked List)는 동적 메모리 할당(dynamic memory allocation)을 기반으로 동작하는 자료 구조로, 여러 개의 노드(Node)들이 모여 이루어진 집합입니다.

각 노드는 실제 값을 저장하는 데이터(data) 부분과 다른 노드를 가리키는 링크(link) 부분, 두 가지로 구성됩니다.

연결 리스트의 종류

C 프로그래밍에서 사용되는 연결 리스트의 종류는 다음과 같습니다.

  • 단일 연결 리스트(Singly Linked List)
  • 이중 연결 리스트(Doubly Linked List)
  • 원형 단일 연결 리스트(Circular Singly Linked List)
  • 원형 이중 연결 리스트(Circular Doubly Linked List)

이중 연결 리스트(Doubly Linked List)

이중 연결 리스트는 각 노드가 이전 노드를 가리키는 포인터(preptr)와 다음 노드를 가리키는 포인터(nextptr)를 모두 가지고 있어, 리스트를 양방향으로 탐색할 수 있다는 점이 특징입니다.

아래 그림은 이중 연결 리스트의 구조를 나타낸 것입니다.

C 언어로 이중 연결 리스트(Doubly Linked List)의 임의 위치에 노드 삽입하기

예제 코드

다음은 이중 연결 리스트를 사용하여 임의의 위치에 노드를 삽입하는 C 프로그램입니다.

#include <stdio.h>
#include <stdlib.h>
struct node {
    int num;
    struct node * preptr;
    struct node * nextptr;
}*stnode, *ennode;
void DlListcreation(int n);
void DlLinsertNodeAtBeginning(int num);
void DlLinsertNodeAtEnd(int num);
void DlLinsertNodeAtAny(int num, int pos);
void displayDlList(int a);
int main(){
    int n,num1,a,insPlc;
    stnode = NULL;
    ennode = NULL;
    printf("\n\n Doubly Linked List : Insert a node at any position :\n");
    printf("-----------------------------------------------------------------------------------\n");
    printf(" Input the number of nodes : ");
    scanf("%d", &n);
    DlListcreation(n);
    a=1;
    displayDlList(a);
    printf(" Input the position ( 1 to %d ) to insert a new node : ",n+1);
    scanf("%d", &insPlc);
    printf(" Input data for the position %d : ", insPlc);
    scanf("%d", &num1);
    DlLinsertNodeAtAny(num1,insPlc);
    a=2;
    displayDlList(a);
    return 0;
}
void DlListcreation(int n){
    int i, num;
    struct node *fnNode;
    if(n >= 1){
        stnode = (struct node *)malloc(sizeof(struct node));
        if(stnode != NULL){
            printf(" Input data for node 1 : "); // 첫 번째 노드에 데이터 할당
            scanf("%d", &num);
            stnode->num = num;
            stnode->preptr = NULL;
            stnode->nextptr = NULL;
            ennode = stnode;
            for(i=2; i<=n; i++){
                fnNode = (struct node *)malloc(sizeof(struct node));
                if(fnNode != NULL){
                    printf(" Input data for node %d : ", i);
                    scanf("%d", &num);
                    fnNode->num = num;
                    fnNode->preptr = ennode;
                    fnNode->nextptr = NULL;
                    ennode->nextptr = fnNode;
                    ennode = fnNode;
                }
                else{
                    printf(" Memory can not be allocated.");
                    break;
                }
            }
        }
        else{
            printf(" Memory can not be allocated.");
        }  
    }
}
void DlLinsertNodeAtAny(int num, int pos){
    int i;
    struct node * newnode, *tmp;
    if(ennode == NULL){
        printf(" No data found in the list!\n");
    }
    else{
        tmp = stnode;
        i=1;
        while(i<pos-1 && tmp!=NULL){
            tmp = tmp->nextptr;
            i++;
        }
        if(pos == 1){
            DlLinsertNodeAtBeginning(num); // 첫 번째 위치에 삽입
        }
        else if(tmp == ennode){
            DlLinsertNodeAtEnd(num); // 마지막 위치에 삽입
        }
        else if(tmp!=NULL){
            newnode = (struct node *)malloc(sizeof(struct node));
            newnode->num = num;
            newnode->nextptr = tmp->nextptr;
            newnode->preptr = tmp;
            if(tmp->nextptr != NULL){
                tmp->nextptr->preptr = newnode; // n+1번째 노드가 새 노드와 연결됨
            }
            tmp->nextptr = newnode; // n-1번째 노드가 새 노드와 연결됨
        }
        else{
            printf(" The position you entered, is invalid.\n");
        }
    }
}
void DlLinsertNodeAtBeginning(int num){
    struct node * newnode;
    if(stnode == NULL){
        printf(" No data found in the list!\n");
    }
    else{
        newnode = (struct node *)malloc(sizeof(struct node));
        newnode->num = num;
        newnode->nextptr = stnode;
        newnode->preptr = NULL;
        stnode->preptr = newnode;
        stnode = newnode;
    }
}
void DlLinsertNodeAtEnd(int num){
    struct node * newnode;
    if(ennode == NULL){
        printf(" No data found in the list!\n");
    }
    else{
        newnode = (struct node *)malloc(sizeof(struct node));
        newnode->num = num;
        newnode->nextptr = NULL;
        newnode->preptr = ennode;
        ennode->nextptr = newnode;
        ennode = newnode;
    }
}
void displayDlList(int m){
    struct node * tmp;
    int n = 1;
    if(stnode == NULL) {
        printf(" No data found in the List yet.");
    }
    else{
        tmp = stnode;
        if (m==1) {
            printf("\n Data entered in the list are :\n");
        }
        else{
            printf("\n After insertion the new list are :\n");
        }
        while(tmp != NULL){
            printf(" node %d : %d\n", n, tmp->num);
            n++;
            tmp = tmp->nextptr; // 현재 포인터가 다음 노드로 이동
        }
    }
}

삽입 로직 살펴보기

DlLinsertNodeAtAny() 함수의 핵심 동작 흐름은 다음과 같습니다.

  • 위치가 1인 경우: 리스트 맨 앞에 새 노드를 삽입합니다(DlLinsertNodeAtBeginning 호출).
  • 마지막 위치인 경우: 리스트 맨 끝에 새 노드를 삽입합니다(DlLinsertNodeAtEnd 호출).
  • 중간 위치인 경우: 해당 위치까지 포인터를 이동한 뒤, 새 노드의 preptrnextptr을 조정하여 앞뒤 노드와 양방향으로 연결합니다.
  • 잘못된 위치인 경우: 유효하지 않은 위치라는 메시지를 출력합니다.

실행 결과

위 프로그램을 컴파일하고 실행하면 다음과 같은 결과가 출력됩니다.

Doubly Linked List : Insert node at any position:
-----------------------------------------------------------------------------------
Input the number of nodes : 5
Input data for node 1 : 23
Input data for node 2 : 12
Input data for node 3 : 11
Input data for node 4 : 34
Input data for node 5 : 10

Data entered in the list are :
node 1 : 23
node 2 : 12
node 3 : 11
node 4 : 34
node 5 : 10
Input the position ( 1 to 6 ) to insert a new node : 5
Input data for the position 5 : 78

After insertion the new list are :
node 1 : 23
node 2 : 12
node 3 : 11
node 4 : 34
node 5 : 78
node 6 : 10