package leetcode.editor.cn;
//将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
//
// 示例:
//
// 输入:1->2->4, 1->3->4
//输出:1->1->2->3->4->4
//
// Related Topics 链表
import org.w3c.dom.stylesheets.LinkStyle;
//Java:合并两个有序链表
public class P21合并两个有序链表{
public void main(String[] args) {
Solution solution = new P21合并两个有序链表().new Solution();
ListNode list1 = new ListNode(0);
list1.next = new ListNode(1);
ListNode list2 = new ListNode(1);
list2.next = new ListNode(2);
ListNode ans = solution.mergeTwoLists(list1, list2);
while (ans != null) {
System.out.println(ans.val);
ans = ans.next;
}
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode mergeTwoLists(ListNode p1, ListNode p2) {
ListNode ans = new ListNode(0);
ListNode temp = ans, l1 = p1, l2 = p2;
while (l1 != null && l2 != null) {
int val1 = l1.val;
int val2 = l2.val;
if (val1 < val2) {
temp.next = l1;
l1 = l1.next;
} else {
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if (l2 != null) {
temp.next = l2;
}
if (l1 != null) {
temp.next = l1;
}
return ans.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}