반응형
단일 연결 리스트
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 | #include <iostream> #include <cstdio> using namespace std; class NODE { private: friend class LIST; int data; NODE *next; }; class LIST { private: NODE *first, *last; public: LIST() { first = last = NULL; } ~LIST() { // 소멸자 코드 } // O(1) void insert(int val) { if (first == NULL) // or last == NULL { NODE *newNode = new NODE; newNode->data = val; first = last = newNode; newNode->next = NULL; } else if (last != NULL) { NODE *newNode = new NODE; newNode->data = val; newNode->next = NULL; last->next = newNode; last = newNode; } } // O(n) int del(int val) { NODE *cur = first; while (1) { if (cur == NULL) return -1; if (cur->data == val && cur == first) { first = first->next; delete cur; return 1; } else if (cur->next->data == val && cur->next == last) { NODE *tmp = last; last = cur; delete tmp; last->next = NULL; return 1; } if (cur->next->data == val) { // 찾았다. NODE *tmp = cur->next; cur->next = cur->next->next; delete tmp; // 노드를 지운다 return 1; } else if (cur->next->data != val) { cur = cur->next; } } } // O(n) int find(int val) { NODE *cur = first; while (1){ if (cur == NULL) return -1; if (cur->data == val) return 1; else if (cur->data != val) cur = cur->next; } } // O(n) void seeAll() { NODE *cur = first; while (cur != NULL) { cout << cur->data << " "; cur = cur->next; } cout << endl; } }; int main() { LIST list; list.insert(100); list.insert(200); list.insert(150); list.seeAll(); list.del(150); list.seeAll(); return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Tutoring > Data Structure' 카테고리의 다른 글
연결리스트 및 응용 예시 문제 (0) | 2018.05.24 |
---|---|
튜터링 템플릿, 체인 (0) | 2018.05.03 |
튜터링 atoi, 후위 표기식 (0) | 2018.04.11 |
튜터링 연습문제 1주차 (0) | 2018.03.21 |
hash (0) | 2018.03.04 |