์๋ ํ์ธ์ ์ฃผ์ธ์ฅ H ์ ๋๋ค.
์ด๋ฒ ๊ธ์ ์ค๋ช ๋๋ฆฌ๊ธฐ ์ ์ ๋จผ์ ์ ์ ํฌ์คํธ๋ฅผ ์ฝ๊ณ ์์ฃผ์๊ธฐ ๋ฐ๋๋๋ค.
modernalchemist.tistory.com/39
[C์ธ์ด] ์ฐ๊ฒฐ๋ฆฌ์คํธ (linked list)
linked representation ๋์ ์ผ๋ก ํฌ๊ธฐ๊ฐ ๋ณํ ์ ์๊ณ ์ญ์ ๋ ์ฝ์ ์์ ๋ฐ์ดํฐ๋ฅผ ์ด๋ํ ํ์๊ฐ ์๋ ์ฐ๊ฒฐ๋ ํํ ์ด ์ฐ๊ฒฐ๋ ํํ์ ํฌ์ธํฐ๋ฅผ ์ฌ์ฉํ์ฌ ๋ฆฌ์คํธ๋ค์ ์ฐ๊ฒฐ. ์ด๋ ํธ๋ฆฌ ๊ทธ๋ํ ์คํ ํ ๋ฑ
modernalchemist.tistory.com
๋จ์ด๋ค์ ์ฐ๊ฒฐํ๋ ์ฝ๋๋ ์ฌ์ด๋ฐ์.
๊ธฐ์กด์ ์งฐ๋ ์ฐ๊ฒฐ๋ฆฌ์คํธ ์ฝ๋์์
typedef int element๋ฅผ ๋ฐฐ์ด์ ํฌํจํ๊ณ ์๋ ๊ตฌ์กฐ์ฒด๋ก ์์ ํด์ฃผ๋ฉด ๋ฉ๋๋ค.
typedef struct{
char name[100]; //๋จ์ด๋ฅผ ์ ์ฅํ๋ ๋ฐฐ์ด
} element;
๊ทธ๋ฆฌ๊ณ print_list() ๋ฉ์๋๋ ๋ฐ์ดํฐ ํ๋์ ์ ์ฅ๋ ๋ฌธ์์ด์ ์ถ๋ ฅํ๋๋ก ์์ ํด๋ด ์๋ค.
void print_list(ListNode* head) {
for (ListNode* p = head; p != NULL; p = p->link) {
printf("%s ->", p->data.name); //element๊ฐ ๊ตฌ์กฐ์ฒด ์ด๊ธฐ ๋๋ฌธ
}
printf("NULL \n");
}
๊ทธ๋ฌ๋ฉด ์ต์ข ์ ์ผ๋ก ์์ ๋ ์ฝ๋๋ฅผ ์์ฑํด๋ณด๋ฉด ์ด๋ ๊ฒ ์์ฑํด๋ณผ ์ ์๊ฒ ์ง์.
์ฌ๊ธฐ์ insert๋ฅผ ์ฌ์ฉํด์๋ ์์ฑํด๋ณผ ์ ์์ํ ๋ฐ ์ ๋ ํ๋ฒ ํ๋ก๊ทธ๋๋ฐ ํด๋ด์ผ ๋๊ฒ ์ต๋๋ค.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[100];
}element;
typedef struct ListNode {
element data;
struct ListNode* link;
} ListNode;
ListNode* insert_first(ListNode* head, element value) {
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p->data = value;
p->link = head;
head = p;
return head;
}
ListNode* insert(ListNode* head, ListNode* pre, element value) {
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p->data = value;
p->link = pre->link;
pre->link = p;
return head;
}
ListNode* delete_first(ListNode* head) {
ListNode* removed;
if (head == NULL) return NULL;
removed = head;
head = removed->link;
free(removed);
return head;
}
ListNode* delete_pre(ListNode* head, ListNode* pre) {
ListNode* removed;
removed = pre->link;
pre->link = removed->link;
free(removed);
return head;
}
void print_list(ListNode* head) {
for (ListNode* p = head; p != NULL; p = p->link) {
printf("%s -> ", p->data.name);
}
printf("NULL\n");
}
int main(void) {
ListNode* head = NULL; //linked list๋ฅผ ๊ฐ๋ฅดํค๋ head pointer
element data;
strcpy(data.name, "C lang");
head = insert_first(head, data);
print_list(head);
strcpy(data.name, "Love");
head = insert_first(head, data);
print_list(head);
strcpy(data.name, "I");
head = insert_first(head, data);
print_list(head);
return 0;
}
'์๋ฃ๊ตฌ์กฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C์ธ์ด]์ฐ๊ฒฐ๋ฆฌ์คํธ ๊ฑฐ๊พธ๋ก ์ถ๋ ฅํ๊ธฐ (์ญ์์ผ๋ก ๋ง๋ค๊ธฐ) (0) | 2020.11.08 |
---|---|
[C์ธ์ด] ์ฐ๊ฒฐ๋ฆฌ์คํธ์์ ํน์ ํ ๊ฐ ํ์ํ๊ธฐ(๋ ธ๋ ํ์ ์๊ณ ๋ฆฌ์ฆ) (1) | 2020.11.06 |
[C์ธ์ด] ์ฐ๊ฒฐ๋ฆฌ์คํธ (linked list) (0) | 2020.11.06 |
[C์ธ์ด] ๋ฐฐ์ด๋ก ๊ตฌํํ ๋ฆฌ์คํธ (0) | 2020.11.06 |
[์๋ฃ๊ตฌ์กฐ] counting sort ๊ณ์์ ๋ ฌ (0) | 2020.08.18 |