题目
https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
思路
方法1、先把俩个链表都放到数组中,排序后再输出成新的链表 时间复杂度和空间复杂度都是o(n)
方法2、构造dummyhead 同时遍历俩个链表,时间复杂度是o(n) 空间复杂度是o(1)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ReverseListNode {
/**
*
* @param l1
* @param l2
* @return 把俩个链表放到一个排序集合中去
* 时间复杂度是o(n) 空间复杂度是o(1)
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
List<Integer> list = new ArrayList<Integer>();
while (l1!=null){
list.add(l1.val);
l1 = l1.next;
}
while (l2!=null){
list.add(l2.val);
l2 = l2.next;
}
Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
ListNode ret = new ListNode(-1);
ListNode dummyHead = ret;
for (Integer integer : list) {
dummyHead.next = new ListNode(integer);
dummyHead = dummyHead.next;
}
return ret.next;
}
/**
*
* @param l1
* @param l2
* @return 时间复杂度o(n) 空间复杂度o(1)
*/
public ListNode mergeTwoListsWay2(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode dummyHead = head;
while (l1!=null&&l2!=null){
if(l1.val<l2.val){
dummyHead.next = l1;
l1 = l1.next;
}else {
dummyHead.next = l2;
l2 = l2.next;
}
dummyHead = dummyHead.next;
}
dummyHead.next = (l1==null?l2:l1);
return head.next;
}
/**
*
* @param args
*/
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
ListNode listNode1 = new ListNode(2);
ListNode listNode2 = new ListNode(3);
ListNode listNode3 = new ListNode(4);
listNode.next = listNode1;
listNode1.next =listNode2;
listNode2.next =listNode3;
ReverseListNode t = new ReverseListNode();
t.mergeTwoLists(listNode,listNode);
System.out.println(1);
}
}
后记
1、构造dummyHead 是链表中重要的操作
2、要会数组转链表