연결 리스트: 노드를 연결해서 만든 리스트
typedef struct Node {
int data;
struct Node* nextNode;
} Node;
Node* CreateNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->nextNode = NULL;
return newNode;
}
int IsEmpty(Node* list) {
if(list == NULL) {
printf("빈 리스트입니다.\n");
return 0;
}
return 0;
}
Node* RemoveNode(Node** head, int data) {
if(IsEmpty(*head)) return NULL;
// 삭제 원하는 데이터 검색
Node* target = SearchNode(*head, data);
if(target == NULL) return NULL;
if(*head == target) *head = target->nextNode;
else {
Node* current = *head;
while(current->nextNode != target) {
current = current->nextNode;
}
current->nextNode = target->nextNode;
}
target->nextNode = NULL;
return target;
}
void DestroyNode(Node* target) {
free(target);
}
Node* SearchNode(Node* list, int data) {
if(IsEmpty(list)) return NULL;
while(list != NULL) {
if(list->data == data) return list;
list = list->nextNode;
}
printf("검색 결과 없음.\n");
return NULL;
}
void AppendNode(Node** head, Node* newNode) {
if(*head == NULL) *head = newNode;
else {
Node* tail = *head;
while(tail->nextNode != NULL) tail = tail->nextNode;
tail->nextNode = newNode;
}
}
void PrintList(Node* current) {
if(!IsEmpty(current)) {
while(current != NULL) {
printf("[%p] %d [%p]\n", current, current->data, current->nextNode);
current = current->nextNode;
}
}
}
void DestroyList(Node** head) {
Node* remove = *head;
Node* next = *head;
while(remove != NULL) {
next = next->nextNode;
free(remove);
remove = next;
}
*head = NULL;
}
int main(void)
{
Node* list = NULL;
Node* newNode = NULL;
int input, data;
newNode = CreateNode(10);
AppendNode(&list, newNode);
newNode = CreateNode(20);
AppendNode(&list, newNode);
newNode = CreateNode(30);
AppendNode(&list, newNode);
PrintList(list);
DestroyNode(RemoveNode(&list, 10));
PrintList(list);
DestroyNode(RemoveNode(&list, 30));
PrintList(list);
DestroyNode(RemoveNode(&list, 20));
PrintList(list);
DestroyList(&list);
return 0;
}