插入表二的值到表一中去以后,要将比较的值也变成这个插入的值
/**
* 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 pos1 = l1;
ListNode pos2 = l2;
ListNode dummy = new ListNode (0);
dummy.next=l1;
ListNode pre = dummy;
while(pos1!=null&&pos2!=null)
{
while(pos1!=null&&pos1.val<=pos2.val)
{
pos1=pos1.next;
pre=pre.next;
}
if(pos1==null)break;
// first pos1.val>pos2.val insert pos2 before pos1 ;
ListNode temp = pos2.next;
pre.next=pos2;
pos2.next=pos1;
// now pos1 is the inset val ,so change pos1
pos2=temp;
pos1=pre.next;
}
if(pos1==null)
{
pre.next=pos2;
}
return dummy.next;
}
}
网友评论