0
点赞
收藏
分享

微信扫一扫

Redis 第一次作业

写心之所想 2024-07-24 阅读 36

思路1:

创建新的链表,遍历原链表,将原链表的节点进行头插到新链表中。

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* next = NULL;
    struct ListNode* new_head = NULL;
    if (head == NULL ||head->next == NULL) // 空链或只有一个结点,直回头
    {
        return head;
    }

    while (head != NULL) {
        next=head->next;
        head->next = new_head;
        new_head = head;
        head = next;
    }
    return new_head;
}

思路2:

创建三个节点,依次进行挪动。

struct ListNode* reverseList(struct ListNode* head) {
    if(head==NULL||head->next==NULL)
    {
        return head;
    }
    struct ListNode* n1,*n2,*n3;
    n1=NULL,n2=head,n3=n2->next;
    while(n2)
    {
        n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3!=NULL)
        n3=n3->next;
    }
    return n1;
}

一张图搞懂上面的核心代码:

如果我的文章对你有帮助,期待你的三连!

举报

相关推荐

第一次python作业

python 第一次作业

前端第一次作业

Java第一次作业

【MySQL】第一次作业

鸿蒙第一次作业

java第一次作业

0 条评论