合并两个已排序的链接列表并将其作为新列表返回。新列表应该通过拼接前两个列表的节点来完成。
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
输入: 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) {
ListNode newlist = l1;
int num = 0;
if ( l1 == null ) {
return l2;
}else if ( l2 == null ) {
return l1;
}
while ( newlist.next != null ) {
newlist = newlist.next;
num++ ;
}
while ( l2 != null ) {
newlist.next = l2;
l2 = l2.next;
newlist = newlist.next;
num++ ;
}
for (int i = 0; i < num; i++) {
newlist = l1;
while( newlist.next != null ) {
if ( newlist.next.val < newlist.val ) {
int box = newlist.val;
newlist.val = newlist.next.val;
newlist.next.val = box;
}
newlist = newlist.next;
}
}
return l1;
}
}
希望我的回答对您有帮助~~