输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
算法思想:
代码:
/**
* 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) {
ListNode p1 = l1;
ListNode p2 = l2;
ListNode result = new ListNode(0);
ListNode p = result;
while(p1!=null && p2!=null) {
if(p1.val < p2.val) {
p.next = p1;
p1 = p1.next;
p = p.next;
} else {
p.next = p2;
p2 = p2.next;
p = p.next;
}
}
if(p1!=null) {
p.next = p1;
}
if(p2!=null) {
p.next = p2;
}
return result.next;
}
}