题目描述:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思想:
新建一个链表,然后比较两个链表中的元素值,将较小的值放到新链表的后端,同时更新那两个输入的链表;
处理一下两个链表长度不一样的情况,直接将较长的链表的后续部分插入到新链表的末尾即可。
PS:思想和归并排序基本一样,只不过一个是数组,一个是链表。
class ListNode{
int val;
ListNode next;
public ListNode(int x) {
val = x;
}
}
public class test1 {
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//处理特殊情况
if(l1 == null || l2 == null) return null;
//新建链表及其指针(头指针必须保存着,不然找不到新链表了)
ListNode head = new ListNode(-1);
ListNode cur = head;
//当两个链表均不为空
while(l1 != null && l2 != null) {
//将较小的结点赋值给新链表
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
}
else {
cur.next = l2;
l2 = l2.next;
}
//更新指针
cur = cur.next;
}
//处理两个链表长度不一样的情况
//注意,这里和归并排序那里不一样,数组的话需要加个循环,链表的话直接赋值就行
if(l1 != null) cur.next = l1;
if(l2 != null) cur.next = l2;
return head.next;
}
//初始化链表
public static void add(ListNode node, int[] data) {
ListNode temp = node;
if(data.length == 0) return;
for(int i = 0; i < data.length; i++) {
temp.next = new ListNode(data[i]);
temp = temp.next;
}
}
//打印链表
public static void LinkedPrint(ListNode node) {
if(node == null) return;
while(node != null) {
System.out.println(node.val + " ");
node = node.next;
}
}
public static void main(String[] args) {
ListNode l1 = new ListNode(-1);
int[] nums1 = {1, 2, 4};
add(l1, nums1);
ListNode l2 = new ListNode(-1);
int[] nums2 = {1, 3, 4};
add(l2, nums2);
ListNode result = mergeTwoLists(l1.next, l2.next);
LinkedPrint(result);
}
}