当前位置:网站首页>LeetCode(剑指 Offer)- 25. 合并两个排序的链表

LeetCode(剑指 Offer)- 25. 合并两个排序的链表

2022-08-09 09:37:00 放羊的牧码

题目链接:点击打开链接

题目大意:

解题思路:

相关企业

  • 字节跳动
  • 微软(Microsoft)
  • 谷歌(Google)
  • 苹果(Apple)
  • 亚马逊(中国)投资有限公司
  • 甲骨文(Oracle)
  • 彭博(Bloomberg)
  • 优步(Uber)
  • Indeed
  • Facebook

AC 代码

  • Java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dum = new ListNode(0), cur = dum;
        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            }
            else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 != null ? l1 : l2;
        return dum.next;
    }
}
  • C++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dum = new ListNode(0);
        ListNode* cur = dum;
        while(l1 != nullptr && l2 != nullptr) {
            if(l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
            }
            else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1 != nullptr ? l1 : l2;
        return dum->next;
    }
};
原网站

版权声明
本文为[放羊的牧码]所创,转载请带上原文链接,感谢
https://lux-sun.blog.csdn.net/article/details/126232402