C언어 코딩도장 Unit 74. 연결 리스트 구현하기 코드를 참고해서 만들었다.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
void addFirst(struct Node *target, int data){
if (target == NULL){
return;
}
struct Node *newNode = malloc(sizeof(struct Node));
newNode->next = target->next;
newNode->prev = target;
newNode->data = data;
target->next = newNode;
if (newNode->next != NULL){
newNode->next->prev = newNode;
}
}
void removeFirst(struct Node *target){
if (target == NULL){
return;
}
struct Node *removeNode = target->next;
target->next = removeNode->next;
removeNode->prev = target;
free(removeNode);
}
int main(){
struct Node *head = malloc(sizeof(struct Node));
head->next = NULL;
addFirst(head, 10);
addFirst(head, 20);
addFirst(head, 30);
addFirst(head, 40);
struct Node *cur = head->next;
while (cur != NULL){
printf("%d\n", cur->data);
cur = cur->next;
}
cur = head->next;
while (cur != NULL){
struct Node *next = cur->next;
free(cur);
cur = next;
}
free(head);
return 0;
}