양방향 연결 리스트는 머리(Head)와 꼬리(Tail)를 모두 가진다는 특징이 있습니다
각 노드는 앞 노드와 뒤 노드의 정보를 모두 저장하고 있습니다
prev | next | prev | next | prev | next | |||
Head | 일반 노드 | Tail |
양방향 연결 리스트 선언
1
2
3
4
5
6
7
8
9
10
11
|
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node *head, *tail;
|
cs |
양방향 연결 리스트 삽입과정
- 삽입할 위치에서 그 앞쪽에 있는 노드가 삽입할 노드를 가리키도록 만듭니다
- 삽입할 노드가 앞쪽에 있는 노드를 가리키도록 만듭니다
- 뒤쪽에 있는 노드가 삽입할 노드를 가리키도록 만듭니다
- 삽입할 노드가 뒤쪽에 있는 노드를 가리키도록 만듭니다
순서를 철저하게 지켜주셔야 오류없이 동작하게 됩니다
양방향 연결 리스트 예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node *head, *tail;
void insert(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
Node* cur;
cur = head->next;
while (cur->data < data && cur != tail) {
cur = cur->next;
}
Node* prev = cur->prev;
prev->next = node;
node->prev = prev;
cur->prev = node;
node->next = cur;
}
void removeFront() {
Node* node = head->next;
head->next = node->next;
Node* next = node->next;
next->prev = head;
free(node);
}
void show() {
Node* cur = head->next;
while (cur != tail) {
printf("%d ", cur->data);
cur = cur->next;
}
}
int main (void){
head = (Node*)malloc(sizeof(Node));
tail = (Node*)malloc(sizeof(Node));
head->next = tail;
head->prev = head;
tail->next = tail;
tail->prev = head;
insert(2);
insert(1);
insert(3);
insert(9);
insert(7);
removeFront();
show();
return 0;
}
|
cs |
양방향 연결 리스트 구현에 있어서 주의할 점
위 소스코드에 덧붙여서 삽입 및 삭제 기능에서의 예외 사항을 처리할 필요가 있습니다
더 이상 삭제할 원소가 없는데 삭제하는 경우 등을 체크해야 합니다
'자료구조와 알고리즘' 카테고리의 다른 글
스택 (0) | 2021.02.27 |
---|---|
연결 리스트 (0) | 2021.02.17 |
자료구조의 개요 (0) | 2021.02.16 |