-
[C] Doubly Circular Linked List기반의 ADT List 연산 구현Programming/C++ 2021. 2. 5. 00:42
c++의 구조체를 이용해서 직접 Doubly Circular Linked List를 구현해봤다
구현한 총 연산은 create, traversal, insert(first, middle, last), delete(first, middle, last)
typedef struct Node { int data; struct Node* next; struct Node* prev; }Node; void create(Node* head) { head = NULL; } void traversal(Node* head) { Node* cur = head; if (head == NULL)return; do { printf("%d ", cur->data); cur = cur->next; } while (cur!= head); printf("\n"); } Node* insertFirst(Node* head, int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; if (head == NULL) { node->next = node; node->prev = node; } else { node->next = head; node->prev = head->prev; head->prev->next = node; head->prev = node; } head = node; return head; } Node* insertLast(Node* head, int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; if (head == NULL) { node->next = node; node->prev = node; head = node; } else { node->next = head; node->prev = head->prev; head->prev->next = node; head->prev = node; } return head; } Node* insert(Node* head, int data, int pos) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; Node* pre = head,*next; for (size_t i = 0; i < pos-1; i++) pre = pre->next; node->prev = pre; node->next = pre->next; pre->next->prev = node; pre->next = node; return head; } Node* deleteFirst(Node* head) { if (head == NULL)return NULL; head->next->prev = head->prev; head->prev->next = head->next; Node* node = head; head = head->next; free(node); return head; } Node* delete(Node* head,int pos) { if (head == NULL)return NULL; Node* pre = head; for (size_t i = 0; i < pos - 1; i++) pre = pre->next; Node* node = pre->next; node->next->prev = pre; pre->next = node->next; free(node); return head; } Node* deleteLast(Node* head) { if (head == NULL)return NULL; Node* pre = head->prev->prev; Node* cur = pre->next; Node* node = cur; pre->next = cur->next; cur->next->prev = pre; free(node); return head; }
코드만 보고는 헷갈렸는데 그림 그려가면서 순서를 정리하니까 감이 잡힌다
'Programming > C++' 카테고리의 다른 글
[C++] Prim Algorithm with Priority Queue (416) 2021.03.22 [C] Circular array기반의 Queue 구현 (424) 2021.01.19 Vector Capacity를 1.5배씩 늘려주는 이유 (420) 2021.01.05 [C++] Dijkstra Algorithm with Priority Queue (395) 2020.05.07 [C++] memset과 fill의 차이/2차원 배열 초기화 함수 (419) 2020.05.02