两个有序链表的插入,类似于归并。两个指针代表两个有序链表,逐个比较将结果插入返回的链表即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if( l1 == null )
{
return l2;
}
if( l2 == null )
{
return l1;
}
ListNode st = new ListNode(0);
ListNode res = st;
while( l1 != null && l2 != null )
{
if( l1.val < l2.val )
{
st.val = l1.val;
l1 = l1.next;
}
else
{
st.val = l2.val;
l2 = l2.next;
}
if(l1 != null || l2 != null )
{
st.next = new ListNode(0);
st = st.next;
}
}
if( l2 != null )
{
st.val = l2.val;
st.next = l2.next;
}
if( l1 != null )
{
st.val = l1.val;
st.next = l1.next;
}
return res;
}
}