0
点赞
收藏
分享

微信扫一扫

Leetcode刷题日记(十四)

芒果六斤半 2022-04-13 阅读 42

又是老台词:欢迎大家来到每晚一度的leetcode刷题日记时间。今晚我们继续来见一见我们的老朋友——递归。递归在平常算法题中应用很多,在链表中自然也是有它的一席之地。下面我们一起来看看有关递归解决反转链表的问题。

直接上题目:

 1.应用迭代解决代码:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;//改指针指向空
        ListNode* curr = head;//该指针指向头结点
        while (curr) {
            ListNode* next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
};

2.应用递归解决问题(比较难理解):

(c++版)

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }
        ListNode* newHead = reverseList(head->next);//采用递归
        head->next->next = head;
        head->next = nullptr;
        return newHead;
    }
};

(C语言版)

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

好啦,今天就分享到这啦,大家早点睡吧,少熬夜。

本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.

举报

相关推荐

0 条评论