Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions Week_01/id_20/LeetCode_21
Original file line number Diff line number Diff line change
@@ -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;

}
}