Skip to content

Instantly share code, notes, and snippets.

@SnowyPainter
Created June 14, 2025 08:54
Show Gist options
  • Save SnowyPainter/77bef1cd36c48c15d671c4a2845b46b7 to your computer and use it in GitHub Desktop.
Save SnowyPainter/77bef1cd36c48c15d671c4a2845b46b7 to your computer and use it in GitHub Desktop.
C프 linked list
#include <stdio.h>
#include <stdlib.h>
typedef struct _node NODE;
typedef struct _list LIST;
typedef struct _node{
int data;
NODE* prev;
NODE* next;
} NODE;
typedef struct _list{
NODE* head;
} LIST;
void push_back(LIST* list, int data) {
if (list->head == NULL) {
NODE* node = (NODE*)malloc(sizeof(NODE));
node->data = data;
node->prev = NULL;
node->next = NULL;
list->head = node;
return;
}
NODE* node = list->head;
while (node->next != NULL) {
node = node->next;
}
NODE* new_node = (NODE*)malloc(sizeof(NODE));
new_node->data = data;
new_node->prev = node;
new_node->next = NULL;
node->next = new_node;
return;
}
void insert(LIST* list, int data, int n) {
int i = 0;
NODE* node = list->head;
while (node->next != NULL) {
if (i == n-1) {
NODE* new_node = (NODE*)malloc(sizeof(NODE));
new_node->data = data;
new_node->prev = node;
new_node->next = node->next;
node->next = new_node;
break;
}
node = node->next;
i++;
}
}
void delete(LIST* list, int n) {
int i = 0;
NODE* node = list->head;
while (node->next != NULL) {
if (i == n) {
NODE* prev = node->prev;
NODE* next = node->next;
prev->next = next;
next->prev = prev;
break;
}
node = node->next;
i++;
}
}
void print_list(LIST* list) {
NODE* node = list->head;
int i = 0;
while (node != NULL) {
printf("NODE[%d] data: %d\n", i, node->data);
node = node->next;
i++;
}
printf("\n");
}
int main(void) {
LIST list = { NULL };
push_back(&list, 10);
push_back(&list, 20);
push_back(&list, 30);
push_back(&list, 40);
print_list(&list);
insert(&list, 25, 1);
print_list(&list);
delete(&list, 3);
print_list(&list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment