Leetcode:Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
给你2个排序好的单链表,返回一个merge的单链表。
链表数据结构:

  public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }

2个单链表各设一个游标,并设一个result节点。
对比2个游标,并将result指向较小的那个游标,较小的游标再向后移一位。

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode head, result, temp1, temp2;
        if (l1 == null && l2 == null)
            return null;
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        head = cur1.val < cur2.val ? cur1 : cur2;
        result = new ListNode(0);
        while (cur1 != null & cur2 != null) {
            result.next = cur1.val < cur2.val ? cur1 : cur2;
            result=result.next;
            if (cur1.val < cur2.val) {
                cur1 = cur1.next;
            } else 
                cur2 = cur2.next;
        }
        if (cur1 == null)
            result.next = cur2;

        if (cur2 == null)
            result.next = cur1;
        return head;
    }
发布了88 篇原创文章 · 获赞 5 · 访问量 9万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章