合并有序链表

merge-two-sorted-lists

http://www.nowcoder.com/questionTerminal/a479a3f0c4554867b35356e0d57cf03d

1. 先处理头结点

1.1 分析

  • 把两个链表中较小的头作为新链表的头
  • 依次比较两个链表未合并部分的头,较小者插入新表的尾
  • 处理未走到尽头的链表

    1.2 代码

    public class Solution {
      public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
          if(l1 == null) return l2;
          if(l2 == null) return l1;
          //先处理头
          ListNode head = (l1.val <= l2.val)? l1:l2;
          ListNode tail = head;
          l1 = (head == l1)? l1.next:l1;
          l2 = (head == l2)? l2.next:l2;
          while(l1 != null && l2 != null)
          {
              if(l1.val <= l2.val){
                  tail.next = l1;
                  l1 = l1.next;
              }else{
                  tail.next = l2;
                  l2 = l2.next;
              }
              tail = tail.next;
          }
          tail.next = (l1 == null)? l2 : l1;
          return head;
      }
    }

    1.3 复杂度

    空间:O(1)
    时间:O(2)

2. 辅助头结点

2.1 分析

先建立辅助头结点,省去了单独处理头的麻烦,最后直接返回辅助头的next

2.2 代码

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        //辅助头
        ListNode head = new ListNode(0);
        ListNode tail = head;
        //以下同上一方法
        while(l1 != null && l2 != null)
        {
            if(l1.val <= l2.val){
                tail.next = l1;
                l1 = l1.next;
            }else{
                tail.next = l2;
                l2 = l2.next;
            }
            tail = tail.next;
        }
        tail.next = (l1 == null)? l2 : l1;
        return head.next;
    }
}
全部评论

相关推荐

书海为家:实习是成为大厂正式员工很好的敲门砖,看您的简历中有一段实习经历,挺好的。我来给一点点小建议,因为毕竟还在学校不像工作几年的老鸟有丰富的项目经验,面试官在面试在校生的时候更关注咱们同学的做事逻辑和思路,所以最好在简历中描述下自己实习时做过项目的完整过程,比如需求怎么来的,你对需求的解读,你想到的解决办法,遇到困难如何找人求助,最终项目做成了什么程度,你从中收获了哪些技能,你有什么感悟。
点赞 评论 收藏
分享
评论
39
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务