# Linked List



img

์—ฐ์†์ ์ธ ๋ฉ”๋ชจ๋ฆฌ ์œ„์น˜์— ์ €์žฅ๋˜์ง€ ์•Š๋Š” ์„ ํ˜• ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ

(ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์—ฐ๊ฒฐ๋œ๋‹ค)

๊ฐ ๋…ธ๋“œ๋Š” ๋ฐ์ดํ„ฐ ํ•„๋“œ์™€ ๋‹ค์Œ ๋…ธ๋“œ์— ๋Œ€ํ•œ ์ฐธ์กฐ๋ฅผ ํฌํ•จํ•˜๋Š” ๋…ธ๋“œ๋กœ ๊ตฌ์„ฑ


# ์™œ Linked List๋ฅผ ์‚ฌ์šฉํ•˜๋‚˜?

๋ฐฐ์—ด์€ ๋น„์Šทํ•œ ์œ ํ˜•์˜ ์„ ํ˜• ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋Š”๋ฐ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์ œํ•œ ์‚ฌํ•ญ์ด ์žˆ์Œ

  1. ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๊ฐ€ ๊ณ ์ •๋˜์–ด ์žˆ์–ด ๋ฏธ๋ฆฌ ์š”์†Œ์˜ ์ˆ˜์— ๋Œ€ํ•ด ํ• ๋‹น์„ ๋ฐ›์•„์•ผ ํ•จ

  2. ์ƒˆ๋กœ์šด ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๋Š” ๊ฒƒ์€ ๋น„์šฉ์ด ๋งŽ์ด ๋“ฌ (๊ณต๊ฐ„์„ ๋งŒ๋“ค๊ณ , ๊ธฐ์กด ์š”์†Œ ์ „๋ถ€ ์ด๋™)


# ์žฅ์ 

  1. ๋™์  ํฌ๊ธฐ

  2. ์‚ฝ์ž…/์‚ญ์ œ ์šฉ์ด

# ๋‹จ์ 

  1. ์ž„์˜๋กœ ์•ก์„ธ์Šค๋ฅผ ํ—ˆ์šฉํ•  ์ˆ˜ ์—†์Œ. ์ฆ‰, ์ฒซ ๋ฒˆ์งธ ๋…ธ๋“œ๋ถ€ํ„ฐ ์ˆœ์ฐจ์ ์œผ๋กœ ์š”์†Œ์— ์•ก์„ธ์Šค ํ•ด์•ผํ•จ (์ด์ง„ ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰ ๋ถˆ๊ฐ€๋Šฅ)

  2. ํฌ์ธํ„ฐ์˜ ์—ฌ๋ถ„์˜ ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์ด ๋ชฉ๋ก์˜ ๊ฐ ์š”์†Œ์— ํ•„์š”

๋…ธ๋“œ ๊ตฌํ˜„์€ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฐ์ดํ„ฐ์™€ ๋‹ค์Œ ๋…ธ๋“œ์— ๋Œ€ํ•œ ์ฐธ์กฐ๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค

// A linked list node 
struct Node 
{ 
  int data; 
  struct Node *next; 
}; 

# Single Linked List

๋…ธ๋“œ 3๊ฐœ๋ฅผ ์ž‡๋Š” ์ฝ”๋“œ๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž

      head         second         third 
        |             |             | 
        |             |             | 
    +---+---+     +---+---+     +----+----+ 
    | 1  | o----->| 2 | o-----> |  3 |  # | 
    +---+---+     +---+---+     +----+----+

์†Œ์Šค ์ฝ”๋“œ (opens new window)



# ๋…ธ๋“œ ์ถ”๊ฐ€

  • ์•ž์ชฝ์— ๋…ธ๋“œ ์ถ”๊ฐ€
void push(struct Node** head_ref, int new_data){
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    new_node->data = new_data;

    new_node->next = (*head_ref);

    (*head_ref) = new_node;
}

  • ํŠน์ • ๋…ธ๋“œ ๋‹ค์Œ์— ์ถ”๊ฐ€
void insertAfter(struct Node* prev_node, int new_data){
    if (prev_node == NULL){
        printf("์ด์ „ ๋…ธ๋“œ๊ฐ€ NULL์ด ์•„๋‹ˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.");
        return;
    }

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    new_node->data = new_data;
    new_node->next = prev_node->next;

    prev_node->next = new_node;
    
}

  • ๋์ชฝ์— ๋…ธ๋“œ ์ถ”๊ฐ€
void append(struct Node** head_ref, int new_data){
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

    struct Node *last = *head_ref;

    new_node->data = new_data;

    new_node->next = NULL;

    if (*head_ref == NULL){
        *head_ref = new_node;
        return;
    }

    while(last->next != NULL){
        last = last->next;
    }

    last->next = new_node;
    return;

}
์ตœ์ข… ์ˆ˜์ • : 12/17/2022, 7:23:59 AM