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
| class MyLinkedList { public: struct LinkedNode { int val; LinkedNode* next; LinkedNode(int val) : val(val), next(nullptr) {} };
MyLinkedList() { _dummyHead = new LinkedNode(0); _size = 0; }
int get(int index) { if (index > _size - 1 || index < 0) return -1; int cnt = -1; LinkedNode* temp = _dummyHead; while (cnt < index) { temp = temp->next; cnt++; } return temp->val; }
void addAtHead(int val) { LinkedNode* newNode = new LinkedNode(val); newNode->next = _dummyHead->next; _dummyHead->next = newNode; _size++; }
void addAtTail(int val) { LinkedNode* temp = _dummyHead; LinkedNode* newNode = new LinkedNode(val); while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; _size++; }
void addAtIndex(int index, int val) { if (index > _size) return; if (index < 0) index = 0; if (index == _size) { addAtTail(val); return; } LinkedNode* temp = _dummyHead; LinkedNode* newNode = new LinkedNode(val); int cnt = 0; while (cnt < index) { temp = temp->next; cnt++; } newNode->next = temp->next; temp->next = newNode; _size++; }
void deleteAtIndex(int index) { if (index < 0 || index > _size - 1) return; LinkedNode* temp = _dummyHead; int cnt = 0; while (cnt < index) { temp = temp->next; cnt++; } LinkedNode* del = temp->next; temp->next = temp->next->next; delete(del); del = nullptr; _size--; }
private: int _size; LinkedNode* _dummyHead; };
int main() { MyLinkedList* myLinkedList = new MyLinkedList(); myLinkedList->addAtHead(1); myLinkedList->addAtTail(3); myLinkedList->addAtIndex(1, 2); cout << myLinkedList->get(1) << endl; myLinkedList->deleteAtIndex(1); cout << myLinkedList->get(1) << endl; return 0; }
|