Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- // 리스트에 담을 데이터의 자료형
- typedef int element;
- // 리스트의 노드 구조체
- typedef struct _Node
- {
- element data; // 각 노드에 담길 자료
- struct _Node* next; // 다음 노드
- } Node;
- // 리스트의 헤더 구조체, 이 구조체로 연결리스트 자체를 표현한다고 생각하면 편하다.
- typedef struct _LinkedList
- {
- Node* head; // 리스트의 맨 앞 노드
- unsigned int size; // 리스트의 노드 개수
- } LinkedList;
- // LinkedList 헤더 구조체라는 이름이 기니깐 List라고 별명짓기
- typedef LinkedList List;
- // 연결리스트 초기화
- void List_Init(List* list)
- {
- list->head = NULL;
- list->size = 0;
- }
- // 연결리스트의 노드를 만들어준다.
- Node* List_CreateNode(Node* n, element e)
- {
- n = (Node*)malloc(sizeof(Node));
- if (n == NULL)
- {
- fprintf(stderr, "malloc() failed while creating new node\n");
- exit(1);
- }
- n->data = e;
- n->next = NULL;
- return n;
- }
- // 리스트의 맨 앞에 item 삽입
- void List_InsertFirst(List* list, element item)
- {
- Node* newNode = NULL;
- newNode = List_CreateNode(newNode, item);
- ++list->size;
- if (list->head == NULL)
- {
- list->head = newNode;
- return;
- }
- newNode->next = list->head;
- list->head = newNode;
- }
- // 리스트의 맨 처음 요소 제거
- void List_RemoveFirst(List* list)
- {
- if (list->head == NULL)
- {
- fprintf(stderr, "Cannot remove from an empty list!\n");
- return;
- }
- Node* remove = list->head;
- list->head = remove->next;
- free(remove);
- --list->size;
- }
- // 리스트의 내용물과 노드개수 출력
- void List_Print(List* list)
- {
- for (Node* i = list->head; i != NULL; i = i->next)
- printf("%2d -> ", i->data);
- printf("NULL (size : %u)\n", list->size);
- }
- int main()
- {
- List list;
- List_Init(&list);
- List_InsertFirst(&list, 10);
- List_InsertFirst(&list, 20);
- List_InsertFirst(&list, 30);
- List_InsertFirst(&list, 40);
- List_InsertFirst(&list, 50);
- List_Print(&list);
- List_RemoveFirst(&list);
- List_RemoveFirst(&list);
- List_Print(&list);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement