Leetcode—707.设计链表【中等】双链表的设计明天再写

2023每日刷题(十七)

Leetcode—707.设计链表

Leetcode—707.设计链表【中等】双链表的设计明天再写_第1张图片

设计单链表实现代码




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


MyLinkedList* myLinkedListCreate() {
    MyLinkedList* mList = (MyLinkedList *)malloc(sizeof(MyLinkedList));
    mList->next = NULL;
    return mList;
}

int myLinkedListGet(MyLinkedList* obj, int index) {
    int j = 0;
    MyLinkedList* p = obj->next;
    if(index < 0) {
        return -1;
    }
    while(j < index && p != NULL) {
        j++;
        p = p->next;
    }
    if(p == NULL) {
        return -1;
    }
    return p->val;
}

void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
    MyLinkedList* p = obj;
    MyLinkedList* s = (MyLinkedList *)malloc(sizeof(MyLinkedList));
    s->val = val;
    s->next = NULL;
    s->next = p->next;
    p->next = s;
}

void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
    MyLinkedList* p = obj;
    MyLinkedList* q = p->next;
    while(q != NULL) {
        p = q;
        q = q->next;
    }
    MyLinkedList* s = (MyLinkedList *)malloc(sizeof(MyLinkedList));
    s->next = NULL;
    s->val = val;
    p->next = s;
}

void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
    MyLinkedList* s = (MyLinkedList *)malloc(sizeof(MyLinkedList));
    s->next = NULL;
    s->val = val;
    int j = 0;
    MyLinkedList* p = obj->next;
    // 记录前驱方便插入结点
    MyLinkedList* q = obj;
    while(j < index && p != NULL) {
        j++;
        q = p;
        p = p->next;
    }
    // index等于链表长度
    if(p == NULL && index == j) {
        q->next = s;
    } else if(p == NULL && index > j) {
        return;
    } else {
        q->next = s;
        s->next = p;
    }
}

void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
    int j = 0;
    MyLinkedList* p = obj->next;
    MyLinkedList* q = obj;
    while(j < index && p != NULL) {
        q = p;
        p = p->next;
        j++;
    }
    if(p != NULL) {
        q->next = p->next;
        free(p);
    }
}

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

/**
 * 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);
*/

运行结果

Leetcode—707.设计链表【中等】双链表的设计明天再写_第2张图片

设计双链表实现代码

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,链表,算法,经验分享,c语言,数据结构)