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.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
思路:
1.比较常规的链表元素排序,有递归和非递归两种做法。
2.非递归,先搞一个头节点。然后找出两个链表的元素值作为头结点的next。注意每次修改后,相应的指针(引用)后移。注意
返回的是头结点的next。
public class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null ) return l2;
if(l2 == null) return l1;
ListNode pre = new ListNode(0);
ListNode head = pre;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
pre.next = l1;
l1 = l1.next;
} else {
pre.next = l2;
l2 = l2.next;
}
pre = pre.next;
}
if(l1 == null) {
pre.next = l2;
} else {
pre.next = l1;
}
return head.next;
}
private class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}
3.递归的方式
public class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
private class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}