赞
踩
难度:easy
方法一:递归:
- // 递归方法
- 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;
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
复杂度分析:
方法二:迭代:
- // 迭代方法
- class Solution {
- public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
- if (list1 == null) {
- return list2;
- }
- if (list2 == null) {
- return list1;
- }
- // 虚拟头节点
- ListNode head = new ListNode();
-
- ListNode cur = head;
- while (list1 != null && list2 != null) {
- if (list1.val < list2.val) {
- cur.next = list1;
- list1 = list1.next;
- } else {
- cur.next = list2;
- list2 = list2.next;
- }
- cur = cur.next;
- }
- // 如果其中有一个链表的元素已经被全部添加到新链表中,则直接将另一个链表接在后面
- cur.next = (list1 == null? list2: list1);
- return head.next;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
复杂度分析:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。