From 11426c2951c51ad8396abdc48110f433e039f3f7 Mon Sep 17 00:00:00 2001 From: lcfgrn Date: Mon, 22 Apr 2019 17:25:39 +0800 Subject: [PATCH] Create LeetCode_21 --- Week_01/id_20/LeetCode_21 | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Week_01/id_20/LeetCode_21 diff --git a/Week_01/id_20/LeetCode_21 b/Week_01/id_20/LeetCode_21 new file mode 100644 index 00000000..6a520dcb --- /dev/null +++ b/Week_01/id_20/LeetCode_21 @@ -0,0 +1,59 @@ +/** + * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 + * + * 示例: + * + * 输入:1->2->4, 1->3->4 + * 输出:1->1->2->3->4->4 + * + * 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) { + if(l1 == null) { + return l2; + } + if(l2 == null) { + return l1; + } + ListNode head = null; + //用于扫描l1 + ListNode p1 = l1; + //用于扫描l2 + ListNode p2 = l2; + if(l1.val < l2.val) { + head = l1; + p1 = l1.next; + } else { + head = l2; + p2 = l2.next; + } + ListNode p = head;//p指向合并列表的最新节点 + while(p1 !=null && p2 != null) { + //比较插入2个链表中元素的大小 + if(p1.val < p2.val) { + //p1插入p后面 + p.next = p1; + p1 = p1.next; + } else { + //p2插入p后面 + p.next = p2; + p2 = p2.next; + } + p = p.next; + } + + if(p1 != null) { + p.next = p1; + } else if(p2 != null){ + p.next = p2; + } + return head; + + } +}