题目地址:
https://www.lintcode.com/problem/merge-two-sorted-lists/description
给定两个单调增的链表,要求将它们合并成一个单调增的链表。代码如下:
public class Solution {
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// write your code here
ListNode dummy = new ListNode(0), cur = dummy;
while (l1 != null || l2 != null) {
if (l1 == null) {
cur.next = l2;
break;
} else if (l2 == null) {
cur.next = l1;
break;
} else {
if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
时间复杂度 ,空间 。