c语言|leetcode707 设计链表 (C语言实现)

直接贴代码

typedef struct { int val; struct ListNode* next; } ListNode; typedef struct { int count; struct ListNode* head; } MyLinkedList; MyLinkedList* myLinkedListCreate() { MyLinkedList* MyLink = (MyLinkedList*)malloc(sizeof(MyLinkedList)); MyLink->count = 0; MyLink->head = NULL; return MyLink; }int myLinkedListGet(MyLinkedList* obj, int index) { if (index < 0 || index >= obj->count) return -1; int i = 0; ListNode* p = obj->head; while (i != index) { p = p->next; i++; } return p->val; }void myLinkedListAddAtHead(MyLinkedList* obj, int val) { ListNode* p = obj->head; struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode)); t->val = val; t->next = p; obj->head = t; obj->count++; }void myLinkedListAddAtTail(MyLinkedList* obj, int val) { ListNode* p = obj->head; if (p == NULL) { myLinkedListAddAtHead(obj, val); return; } while (p->next != NULL) { p = p->next; } struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode)); t->val = val; t->next = NULL; p->next = t; obj->count++; }void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) { if (index > obj->count) return; else if (index <= 0) { myLinkedListAddAtHead(obj, val); return; // 因没有return出bug,导致obj->count++了两次 } else if (index == obj->count) { myLinkedListAddAtTail(obj, val); return; } else { ListNode* p = obj->head; int i = 0; while (i != index) { i++; if (i == index) break; p = p->next; } if (i == index) { struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode)); t->val = val; t->next = p->next; p->next = t; } } obj->count++; return; }void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) { ListNode* p = obj->head; if (index < 0 || index >= obj->count) return; if (index == 0) { obj->head = p->next; obj->count--; return; } int i = 0; while (i != index) { i++; if (i == index) break; //while 条件判断的时间 是循环体执行结束之后 p = p->next; } if (i == index) { p->next = p->next->next; obj->count--; return; } }void myLinkedListFree(MyLinkedList* obj) { free(obj->head); //应该要每个结点都free,obj也要free,不过leetcode并没有判错 }/** * Your MyLinkedList struct will be instantiated and called as such: * MyLinkedList* obj = myLinkedListCreate(); * int param_1 = myLinkedListGet(obj, index); * myLinkedListAddAtHead(obj, val); * myLinkedListAddAtTail(obj, val); * myLinkedListAddAtIndex(obj, index, val); * myLinkedListDeleteAtIndex(obj, index); * myLinkedListFree(obj); */

【c语言|leetcode707 设计链表 (C语言实现)】

    推荐阅读