链表——合并和删除元素之递归

讲真,自学习链表以后,都是认为链表很好用,只是写着麻烦,而且容易写错

于是乎,一直以来都是尽量避免用链表的,虽然麻烦,但是还是会写。

今天刷题遇到波操作刷新了我写链表的mode,简直太帅了。

以前我写代码,比如合并两有序链表是这样的:

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
    ListNode *mergeTwoLists(ListNode *list1, ListNode *list2)
    {
        ListNode *node1 = list1, *node2 = list2;
        if (list1 == NULL)
            return list2;
        if (list2 == NULL)
            return list1;
        if (list1->val > list2->val)
        {
            node1 = list2;
            node2 = list1;
            //更小的头
        }
        ListNode *head = node1;
        while (node2)
        {
            //以node1为主,将node2移动
            //如果2比1->next大,那么插入
            // 1无next,接上2,break
            if (node1->next == NULL)
            {
                node1->next = node2;
                break;
            }
            if (node1->next->val >= node2->val)
            {
                ListNode *n = node2->next;
                node2->next = node1->next;
                node1->next = node2;
                node1 = node1->next;
                node2 = n;
            }
            else
                node1 = node1->next;
        }
        return head;
    }
};
合并

这一般的写法,真的看(写)起来很麻烦

现在我写代码,比如合并是这样的:

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
    ListNode *mergeTwoLists(ListNode *list1, ListNode *list2)
    {
        if (list1 == NULL)
            return list2;
        if (list2 == NULL)
            return list1;
        if (list1->val < list2->val)
        {
            list1->next = mergeTwoLists(list1->next, list2);
            return list1;
        }
        else
        {
            list2->next = mergeTwoLists(list1, list2->next);
            return list2;
        }
    }
};
new--合并

巨帅!!!

从时间复杂度分析两者都是一样的O(m+n),但是递归终究是递归,要慢一点,但但但是,帅阿!!!

进一步,用递归写删除:

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        if (head == NULL)
            return NULL;
        else
        {
            if (head->val == val)
                return removeElements(head->next, val);
            else
            {
                head->next = removeElements(head->next, val);
                return head;
            }
        }
    }
};
new--删除

舒畅!!!

 

posted @ 2022-02-19 14:42  Renhr  阅读(36)  评论(0)    收藏  举报