·get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
·addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
·addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
·addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
·deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
代码示例如下
typedefstructMyLinkedList_t { int val; structMyLinkedList_t *next; } MyLinkedList;
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ intmyLinkedListGet(MyLinkedList *obj, int index) { if (index < 0 || obj->next == NULL) { return-1; } int now = 0; MyLinkedList *listNow = obj->next; while (now < index) { if (listNow == NULL) { return-1; }
listNow = listNow->next; now++; }
if (listNow != NULL) { return listNow->val; }
return-1; }
/** 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. */ voidmyLinkedListAddAtHead(MyLinkedList *obj, int val) { MyLinkedList *Node = (MyLinkedList *)malloc(sizeof(MyLinkedList)); Node->val = val; Node->next = NULL;
/** Append a node of value val to the last element of the linked list. */ voidmyLinkedListAddAtTail(MyLinkedList *obj, int val) { MyLinkedList *Node = (MyLinkedList *)malloc(sizeof(MyLinkedList)); Node->val = val; Node->next = NULL;
/** 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. */ voidmyLinkedListAddAtIndex(MyLinkedList *obj, int index, int val) { if (index <= 0) { myLinkedListAddAtHead(obj, val); }
int now = 0; MyLinkedList *nowList = obj->next; while (nowList->next != NULL) { if (now == index - 1) { break; } nowList = nowList->next; now++; }
/** Delete the index-th node in the linked list, if the index is valid. */ voidmyLinkedListDeleteAtIndex(MyLinkedList *obj, int index) { MyLinkedList *r; if (index < 0 || obj->next == NULL) { return; }
if (index == 0) { r = obj->next; obj->next = obj->next->next; free(r); return; }
MyLinkedList *nowList = obj->next; int now = 0; while (nowList->next != NULL) { if (now == index - 1) { break; } nowList = nowList->next; now++; }
if (now == index - 1 && nowList->next != NULL) { r = nowList->next; nowList->next = nowList->next->next; free(r); } }