力扣日常刷题——(206反转链表、21合并两个有序链表)

  1. 206.反转链表

题目:206. 反转链表 - 力扣(LeetCode)

①解决思路

方法1:使用三个指针pre,cur,next分别指向上一个节点,本节点和下一节点,每次将cur指向next的指针改成指向pre,这之后使这三指针都向后移,不断迭代得到结果。

方法2:创建一个新链表,将各个节点分别头插到新链表中,最后返回新链表。

②代码实践

方法1
struct ListNode* reverseList(struct ListNode* head)
{
    struct ListNode* pre = NULL, *cur = head,*next;
    if (head == NULL)
    {
        return NULL;
    }
    next = head->next;
    
    while (cur)
    {
        cur->next = pre;
        pre = cur;
        cur = next;
        if (next)
        {
            next = next->next;
        }
    }

    return pre;
}

方法2
struct ListNode* reverseList(struct ListNode* head)
{
    if (head == NULL)
    {
        return NULL;
    }
    struct ListNode* cur = head;
    struct ListNode* newhead = NULL;


    while (cur)
    {
        struct ListNode* next = cur->next;

        //头插
        cur->next = newhead;
        newhead = cur;
        cur =next;
    }

    return newhead;
}
  1. 21.合并两个有序链表

题目:21. 合并两个有序链表 - 力扣(LeetCode)

①解决思路

方法1:分别比较两个链表中对应两个的值,创建一个新链表,将其中较小的值尾插到新链表上,当某一链表元素数值均插入完成时,再将另一个链表剩余的部分尾插到新链表上,最后返回新链表。

②代码实践

方法1
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    if (!list1)
    {
        return list2; 
    }
    if (!list2)
    {
        return list1; 
    }
    struct ListNode* cur1 = list1, *cur2 = list2, *head = NULL, *tail = NULL;

    while (cur1 && cur2)
    {
        if(cur1->val < cur2->val)
        {
            if( head == NULL)
            {
               head = tail = cur1;
            }
            else
            {
                tail->next = cur1;
                tail = tail->next;
            }
            cur1 = cur1->next;
        }
        else
        {
            if ( head == NULL)
            {
                head = tail = cur2;
            }
            else
            {
                tail->next = cur2;
                tail = tail->next;
            }
                cur2 = cur2->next;
        }
    }

    if (cur1)
    {
        tail->next = cur1;
    }

    if (cur2)
    {
        tail->next = cur2;
    }

    return head;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值