0Pricing
C Academy · 강의

삽입과 삭제

리스트를 수정합니다

삽입과 삭제은(는) CoddyKit의 무료 C Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

목록 수정하기

연결 목록의 장점은 삽입과 삭제가 저렴하다는 것입니다. 배열처럼 요소를 이동하는 대신 포인터를 재배치합니다.

이 단원에서는 여러 위치에 노드를 삽입하고 제거하는 방법을 다룹니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *head = make(2);
    printf("start: %d\n", head->value);
    free(head);
    return 0;
}

앞쪽에 삽입하기

헤드에 삽입하는 작업은 O(1)입니다. 새 노드를 만들고, 새 노드의 next가 현재 헤드를 가리키게 한 다음, 헤드를 새 노드로 갱신합니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *head = make(2);
    struct Node *fresh = make(1);
    fresh->next = head;
    head = fresh;
    printf("%d -> %d\n", head->value, head->next->value);
    return 0;
}

이중 포인터를 전달하는 이유

함수 내부에서 헤드를 변경하려면 헤드의 주소인 struct Node **를 전달해야 합니다.

그렇지 않으면 함수는 지역 복사본만 수정하므로 호출자의 헤드는 변경되지 않습니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

void push(struct Node **head, int v) {
    struct Node *n = make(v);
    n->next = *head;
    *head = n;
}

int main(void) {
    struct Node *head = NULL;
    push(&head, 5);
    push(&head, 4);
    printf("%d %d\n", head->value, head->next->value);
    return 0;
}

끝에 삽입하기

뒤에 추가하려면 마지막 노드까지 순회한 다음, 새 노드를 마지막 노드의 next에 연결해야 합니다.

목록이 비어 있으면 새 노드가 헤드가 됩니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

void append(struct Node **head, int v) {
    struct Node *n = make(v);
    if (!*head) { *head = n; return; }
    struct Node *p = *head;
    while (p->next) p = p->next;
    p->next = n;
}

int main(void) {
    struct Node *head = NULL;
    append(&head, 1); append(&head, 2);
    printf("%d %d\n", head->value, head->next->value);
    return 0;
}

노드 뒤에 삽입하기

중간에 삽입하려면 삽입할 위치 앞의 노드를 찾은 다음, 새 노드를 해당 노드와 현재 후속 노드 사이에 연결합니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

void insert_after(struct Node *node, int v) {
    struct Node *n = make(v);
    n->next = node->next;
    node->next = n;
}

int main(void) {
    struct Node *head = make(1);
    head->next = make(3);
    insert_after(head, 2);
    printf("%d %d %d\n", head->value, head->next->value, head->next->next->value);
    return 0;
}

연산 순서가 중요합니다

연결을 바꿀 때는 이전 노드의 next를 변경하기 전에 항상 새 노드의 next를 설정해야 합니다.

반대로 하면 목록의 나머지 부분을 가리키는 참조를 잃게 됩니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *a = make(1), *c = make(3);
    a->next = c;
    struct Node *b = make(2);
    b->next = a->next;
    a->next = b;
    printf("%d %d %d\n", a->value, b->value, c->value);
    return 0;
}

첫 번째 노드 삭제하기

헤드를 제거하려면 헤드를 저장하고, 헤드를 head->next로 이동한 다음, 이전 헤드를 해제합니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

void pop(struct Node **head) {
    if (!*head) return;
    struct Node *old = *head;
    *head = old->next;
    free(old);
}

int main(void) {
    struct Node *head = make(1);
    head->next = make(2);
    pop(&head);
    printf("new head: %d\n", head->value);
    free(head);
    return 0;
}

값으로 삭제하기

주어진 값을 가진 노드를 제거하려면 이전 노드를 추적해야 합니다. 그러면 prev->next = target->next를 설정하여 대상 노드를 건너뛸 수 있습니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

void del(struct Node **head, int v) {
    struct Node *cur = *head, *prev = NULL;
    while (cur && cur->value != v) { prev = cur; cur = cur->next; }
    if (!cur) return;
    if (prev) prev->next = cur->next; else *head = cur->next;
    free(cur);
}

int main(void) {
    struct Node *head = make(1);
    head->next = make(2);
    head->next->next = make(3);
    del(&head, 2);
    printf("%d %d\n", head->value, head->next->value);
    return 0;
}

헤드인 경우 처리하기

대상이 헤드일 때 삭제에는 특별한 경우가 있습니다. 이전 노드가 없으므로 헤드 포인터를 직접 갱신해야 합니다.

위에서 본 것처럼 이중 포인터를 사용하면 이 작업을 깔끔하게 처리할 수 있습니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *head = make(1);
    head->next = make(2);
    struct Node *old = head;
    head = head->next;
    free(old);
    printf("head now %d\n", head->value);
    free(head);
    return 0;
}

메모리 누수 방지하기

목록에서 제거하는 모든 노드는 free해야 합니다. 노드를 해제하지 않고 버리면 해당 노드가 사용하던 메모리가 누수됩니다.

마찬가지로 노드가 아직 연결된 상태에서는 절대 해제하지 마세요. 매달린 포인터가 생성됩니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *n = make(7);
    free(n);
    printf("node freed, no leak\n");
    return 0;
}

삽입 시 정렬 순서 유지하기(선택 사항)

정렬된 순서로 삽입하는 것은 일반적인 변형입니다. 값이 들어갈 위치를 찾을 때까지 순회한 다음 해당 위치에 연결합니다.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

void insert_sorted(struct Node **head, int v) {
    struct Node *n = make(v);
    if (!*head || (*head)->value >= v) { n->next = *head; *head = n; return; }
    struct Node *p = *head;
    while (p->next && p->next->value < v) p = p->next;
    n->next = p->next; p->next = n;
}

int main(void) {
    struct Node *head = NULL;
    insert_sorted(&head, 3);
    insert_sorted(&head, 1);
    insert_sorted(&head, 2);
    for (struct Node *p = head; p; p = p->next) printf("%d ", p->value);
    printf("\n");
    return 0;
}

빠른 확인

목록 수정에 대한 이해도를 확인해 보세요.

복습

노드를 삽입하고 삭제하는 방법을 배웠습니다.

  • 앞쪽 삽입은 O(1)이지만, 뒤에 추가하거나 정렬된 위치에 삽입하려면 순회해야 합니다.
  • 헤드가 변경될 수 있을 때는 이중 포인터를 사용합니다.
  • 연결을 바꿀 때는 주의하세요. 다시 연결하기 전에 새 노드의 next를 설정해야 합니다.
  • 삭제할 때는 이전 노드를 추적하고, 제거한 노드는 항상 free해야 합니다.

자주 묻는 질문

“삽입과 삭제” 강의는 무료인가요?

네 — “삽입과 삭제” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C Academy 강의 전체를 잠금 해제할 수 있습니다. C Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“삽입과 삭제”에서 뭘 배우나요?

리스트를 수정합니다 브라우저에서 직접 실행하는 실습 코드로 C Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

C Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 C Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“삽입과 삭제” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 C Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 C Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 단일 연결 리스트
  2. 삽입과 삭제
  3. 순회와 검색
  4. 이중 연결 리스트
← C Academy(으)로 돌아가기