0
点赞
收藏
分享

微信扫一扫

day26_LC学习计划:数据结构基础

夏沐沐 2022-04-01 阅读 42

 这其实是简单题吧= =

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* swapPairs(struct ListNode* head){
    struct ListNode* newHead=malloc(sizeof(struct ListNode));
    newHead->next=head;

    struct ListNode* cur=newHead;
    while(cur->next&&cur->next->next){
        struct ListNode* prev=cur->next,* post=cur->next->next;
        cur->next=post;
        prev->next=post->next;
        post->next=prev;
        cur=prev;
    }
    return newHead->next;
}

 依旧不是很会递归,大概理解一下。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* swapPairs(struct ListNode* head){
    if(head==NULL||head->next==NULL){
        return head;
    }
    struct ListNode* newHead=head->next;
    head->next=swapPairs(newHead->next);
    newHead->next=head;
    return newHead;
}

LC没说明清楚obj是否是头节点也太坑了。。= = 

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


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

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

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

void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
    MyLinkedList* cur=obj;
    while(cur->next){
        cur=cur->next;
    }
    MyLinkedList* newList=malloc(sizeof(MyLinkedList));
    newList->val=val;
    newList->next=NULL;
    cur->next=newList;
}

void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
    if(index<0) myLinkedListAddAtHead(obj,val);
    MyLinkedList* cur=obj;
    while(cur->next!=NULL&&index!=0){
        cur=cur->next;
        index--;
    }
    if(cur->next==NULL&&index!=0) return;
    MyLinkedList* newList=malloc(sizeof(MyLinkedList));
    newList->val=val;
    newList->next=cur->next;
    cur->next=newList;
}

void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
    MyLinkedList* cur=obj;
    while(cur->next&&index!=0){
        cur=cur->next;
        index--;
    }
    if(cur->next){
        cur->next=cur->next->next;
    }
}

void myLinkedListFree(MyLinkedList* obj) {
    free(obj);
}

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

相关推荐

0 条评论