메인함수
int main()
{
/*----------헤드와 테일 선언---------------*/
Node* head = (Node*)malloc(sizeof(Node));
Node* tail = (Node*)malloc(sizeof(Node));
head->next = tail;
head->prev = NULL;
tail->next = NULL;
tail->prev = head;
/*---------------노드 추가-------------------*/
insertFirst(head,10);
insertFirst(head, 20);
/*----------------노드 출력----------------*/
print(head, tail);
/*----------------노드 제거-----------------*/
removeFirst(head);
/*----------------노드 출력----------------*/
print(head,tail);
/*----------------메모리 해제----------------*/
finish(head);
}
노드 선언 구조체
typedef struct Node
{
int data;
struct Node* prev;
struct Node* next;
}Node;
노드 생성함수
Node* makeNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->next = NULL;
node->prev = NULL;
node->data = data;
return node;
}
헤드 뒤에 노드 추가 함수
void insertFirst(Node*target,int data)
{
Node* node = makeNode(data);
Node* tmp = target->next;
target->next = node;
node->next = tmp;
tmp->prev = node;
node->prev=target;
}
헤드 뒤 노드 삭제 함수
void removeFirst(Node* target)
{
Node* node = target->next;
Node* tmp = target->next;
target->next = node->next;
node->next->prev = target;
free(tmp);
}
모든 동작후 메모리 해제해주는 함수
void finish(Node*target)
{
Node* curr = target;
Node* tmp;
while (curr != NULL)
{
tmp = curr->next;
free(curr);
curr = tmp;
}
}
728x90
'Data structure' 카테고리의 다른 글
연결리스트로 Stack 구현하기 - c언어 (0) | 2022.03.14 |
---|---|
단방향 연결리스트(c언어) (0) | 2022.03.05 |
dfs, bfs (0) | 2021.12.05 |
유클리드 호제법 (0) | 2021.12.02 |
에라토스의 체(python) (0) | 2021.12.02 |