Advertisement
nyhryan

Untitled

Aug 1st, 2023
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.29 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // 리스트에 담을 데이터의 자료형
  5. typedef int element;
  6.  
  7. // 리스트의 노드 구조체
  8. typedef struct _Node
  9. {
  10.     element data;        // 각 노드에 담길 자료
  11.     struct _Node* next;  // 다음 노드
  12. } Node;
  13.  
  14. // 리스트의 헤더 구조체, 이 구조체로 연결리스트 자체를 표현한다고 생각하면 편하다.
  15. typedef struct _LinkedList
  16. {
  17.     Node* head;        // 리스트의 맨 앞 노드
  18.     unsigned int size; // 리스트의 노드 개수
  19. } LinkedList;
  20.  
  21. // LinkedList 헤더 구조체라는 이름이 기니깐 List라고 별명짓기
  22. typedef LinkedList List;
  23.  
  24. // 연결리스트 초기화
  25. void List_Init(List* list)
  26. {
  27.     list->head = NULL;
  28.     list->size = 0;
  29. }
  30.  
  31. // 연결리스트의 노드를 만들어준다.
  32. Node* List_CreateNode(Node* n, element e)
  33. {
  34.     n = (Node*)malloc(sizeof(Node));
  35.     if (n == NULL)
  36.     {
  37.         fprintf(stderr, "malloc() failed while creating new node\n");
  38.         exit(1);
  39.     }
  40.     n->data = e;
  41.     n->next = NULL;
  42.  
  43.     return n;
  44. }
  45.  
  46. // 리스트의 맨 앞에 item 삽입
  47. void List_InsertFirst(List* list, element item)
  48. {
  49.     Node* newNode = NULL;
  50.     newNode = List_CreateNode(newNode, item);
  51.     ++list->size;
  52.  
  53.     if (list->head == NULL)
  54.     {
  55.         list->head = newNode;
  56.         return;
  57.     }
  58.  
  59.     newNode->next = list->head;
  60.     list->head = newNode;
  61. }
  62.  
  63. // 리스트의 맨 처음 요소 제거
  64. void List_RemoveFirst(List* list)
  65. {
  66.     if (list->head == NULL)
  67.     {
  68.         fprintf(stderr, "Cannot remove from an empty list!\n");
  69.         return;
  70.     }
  71.  
  72.     Node* remove = list->head;
  73.     list->head = remove->next;
  74.     free(remove);
  75.     --list->size;
  76. }
  77.  
  78. // 리스트의 내용물과 노드개수 출력
  79. void List_Print(List* list)
  80. {
  81.     for (Node* i = list->head; i != NULL; i = i->next)
  82.         printf("%2d -> ", i->data);
  83.     printf("NULL (size : %u)\n", list->size);
  84. }
  85.  
  86. int main()
  87. {
  88.     List list;
  89.     List_Init(&list);
  90.  
  91.     List_InsertFirst(&list, 10);
  92.     List_InsertFirst(&list, 20);
  93.     List_InsertFirst(&list, 30);
  94.     List_InsertFirst(&list, 40);
  95.     List_InsertFirst(&list, 50);
  96.  
  97.     List_Print(&list);
  98.  
  99.     List_RemoveFirst(&list);
  100.     List_RemoveFirst(&list);
  101.    
  102.     List_Print(&list);
  103.  
  104.     return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement