Question:
Given two sorted linked list, and merge them without using extra space (using constant space is allowed). For example, if 1 -> 2 -> 5 merges with 2 -> 4 -> 5, we have 1 -> 2 -> 4 -> 5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null ) return l2;
if (l2 == null ) return l1;
ListNode head = null;
ListNode current = null;
if (l1.val <= l2.val) {
head = l1;
l1 = l1.next;
} else {
head = l2;
l2 = l2.next;
}
current = head;
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 = l1;
if (l2 != null) current.next = l2;
return head;
}
}
blog.youkuaiyun.com/beiyetengqing
本文介绍了一种在常数空间复杂度下合并两个已排序链表的方法。通过比较两个链表节点的值,将较小值节点连接到结果链表中,直至其中一个链表遍历完成。最后将未结束的链表剩余部分直接连接到结果链表末尾。

被折叠的 条评论
为什么被折叠?



