**问题描述:
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.**
我的思路:由于最近在复习归并排序,所以就采取了类似的方法,大牛勿喷,欢迎指点
下面附上代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(0);
ListNode last = new ListNode(0);
l3.next = last;
if(l1==null&&l2==null)
return null;
if(l1==null&&l2!=null)
return l2;
if(l1!=null&&l2==null)
return l1;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
ListNode temp = l1;
l1 = l1.next;
temp.next = null;
last.next = temp;
last = temp;
}
else{
ListNode temp = l2;
l2 = l2.next;
temp.next = null;
last.next = temp;
last = temp;
}
if(l1==null){
last.next = l2;
break;
}
if(l2==null){
last.next = l1;
break;
}
}
return l3.next.next;
}
}
下面是一个更简洁的解法:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode fakeHead = new ListNode(0);
ListNode current = fakeHead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
if (l1 == null) current.next = l2;
if (l2 == null) current.next = l1;
return fakeHead.next;
}