You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
186
194
int myLinkedListGet(MyLinkedList* obj, int index) {
187
-
MyLinkedList *cur = obj->next;
188
-
for (int i = 0; cur != NULL; i++){
189
-
if (i == index){
190
-
return cur->val;
191
-
}
192
-
else{
193
-
cur = cur->next;
194
-
}
195
+
if (index < 0 || index >= obj->size) return -1;
196
+
197
+
Node* cur = obj->data;
198
+
while (index-- >= 0) {
199
+
cur = cur->next;
195
200
}
196
-
return -1;
201
+
202
+
return cur->val;
197
203
}
198
204
199
205
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
200
206
void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
221
230
void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
0 commit comments