Linked List 의 기본적 삽입 삭제를 하고 있는 코드이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | #define _CRT_SECURE_NO_WARNINGS #include <cstdio> typedef struct node { node* Next; int data; node() { Next = NULL; data = 0; } }Node; typedef struct list { Node* Head; int length; list() { Head = NULL; length = 0; } }List; void add(List* l, int item) { Node* temp = new Node; temp->data = item; if (l->Head == NULL) { l->Head = temp; } else { if (l->Head->data > item) { temp->Next = l->Head; l->Head = temp; } else { Node* temp2 = l->Head; Node* temp3 = NULL; while (true) { if (temp2 == NULL || temp2->data > item ) break; temp3 = temp2; temp2 = temp2->Next; } if (temp2 == l->Head) { temp2->Next = temp; } else { temp3->Next = temp; temp->Next = temp2; } } } l->length++; } void remove(List* l, int item) { if (!l->length) { printf("빈 리스트"); return; } Node* temp = l->Head; Node* temp2 = NULL; if (l->Head->data == item) { l->Head = l->Head->Next; if (length == 1) temp = NULL; else delete temp; } else { while (temp) { if (temp->data == item) { temp2->Next = temp->Next; delete temp; l->length--; return; } temp2 = temp; temp = temp->Next; } } } void clear(List* l) { Node* temp = NULL; while (true) { if (l->length == 1) break; temp = l->Head; l->Head = l->Head->Next; delete temp; l->length--; } l->Head = NULL; l->length--; } Node* is_in_list(List* l, int item) { if (!l->length) printf("빈 리스트입니다"); Node* temp = l->Head; while (true) { if (temp == NULL) { printf("찾는 데이터가 없습니다."); return NULL; } if (temp->data == item) { printf("데이터를 찾았습니다."); return temp; } temp = temp->Next; } } int get_length(List* l) { return l->length; } bool is_empty(List* l) { if (!l->length) return true; else return false; } void display(List* l) { if (!l->length) { printf("데이터가 없습니다."); return; } Node* temp = l->Head; while (temp) { printf("%d,", temp->data); temp = temp->Next; } } int main() { List l; add(&l, 10); add(&l, 4); add(&l, 5); add(&l, 3); add(&l, 20); display(&l); printf("\n"); printf("%d\n",is_empty(&l)); is_in_list(&l, 3); remove(&l, 3); printf("\n"); clear(&l); printf("\n%d\n", is_empty(&l)); display(&l); return 0; } | cs |
'자료구조' 카테고리의 다른 글
스택 , 큐, 트리 그리고 깊이탐색과 넓이탐색 (0) | 2018.05.26 |
---|---|
Double Linked List (0) | 2018.05.26 |
두개의 리스트를 합치는 코드 (0) | 2018.05.26 |
트리 연산과 깊이 및 넓이탐색 (0) | 2018.05.26 |
스택을 이용한 미로찾기 (0) | 2018.05.26 |