Leetcode 707. 设计链表(Medium)

typedef struct {
    int val;
    struct MyLinkedList* next;
} MyLinkedList;

MyLinkedList* myLinkedListCreate() {
    //这个题必须用虚拟头指针,参数都是一级指针,头节点确定后没法改指向了!!!
    MyLinkedList*head=(MyLinkedList*)malloc(sizeof(MyLinkedList));
    head->next=NULL;
    return head;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int myLinkedListGet(MyLinkedList* obj, int index) {
    MyLinkedList*cur= obj->next;
    for(int i=0; cur!=NULL;i++){
        if(i==index) {return cur->val;}
        else {cur=cur->next;}
    }
    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. */
void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
    MyLinkedList*node=(MyLinkedList*)malloc(sizeof(MyLinkedList));
    node->val=val;
    node->next=obj->next;
    obj->next=node;
}

void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
    MyLinkedList*tail=(MyLinkedList*)malloc(sizeof(MyLinkedList));
    tail->val=val;
    tail->next=NULL;
    MyLinkedList*cur=obj;
    while(cur->next!=NULL){cur=cur->next;}
    cur->next=tail;
}
/** 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. */
void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
    if (index == 0){
        myLinkedListAddAtHead(obj, val);
        return;
    }
    MyLinkedList *cur = obj->next;
    for(int i=1; cur!=NULL;i++){
        if(i==index){
            MyLinkedList*node=(MyLinkedList*)malloc(sizeof(MyLinkedList));
            node->val=val;
            node->next=cur->next;
            cur->next=node;
            return;
        }else{
            cur=cur->next;
        }
    }
}

void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
    if(index==0){
        MyLinkedList*temp=obj->next;
        if(temp!=NULL){
            obj->next=temp->next;
            free(temp);
        }
        return;
    }
    MyLinkedList*cur=obj->next;
    for(int i=1;cur!=NULL;i++){  //超过范围 cur不会继续
        if(i==index){
            MyLinkedList*temp=cur->next;
            if(cur!=NULL){              //要删除的结点存不存在
                cur->next=temp->next;
                free(temp);
            }
            return;
        }else{
            cur=cur->next;
        }
    }
}

void myLinkedListFree(MyLinkedList* obj) {
      while(obj != NULL){
        MyLinkedList *tmp = obj;
        obj = obj->next;
        free(tmp);
    }
}

你可能感兴趣的:(LeetCode,数据结构,链表,leetcode,数据结构)