您的位置:首页 > 其它

( Leetcode 21 ) Merge Two Sorted Lists

2016-05-13 20:23 399 查看
题目:Merge Two Sorted Lists

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.

解题思路:

虽然这道题比较简单,首先人人都能想到最基本的那种解法,即设置两个指针来依次比较。但是下面我说一种完全不同的思路

首先思路是以链表L1为中心链表,最后返回L1,L2链表是插入到L1链表上面的,总的是靠来回交换两个链表完成的。

1. 比较L1和L2的头结点,如果L1头结点比L2大,那么交换着两个结点

2. 设置p指向L1,依次和L2结点大小比较,如果p的下一个结点比L2结点大,那么将L2的后半段接到L1后面,L1的后半段变成L2链表

3. 重复1 和 2.

具体看下面的Java代码:

public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
//最终的返回结果是以l1为中心链,l2往l1上面插结点
ListNode tmp;
if (l1.val > l2.val) {   //交换两个头结点
tmp = l2;
l2 = l1;
l1 = tmp;
}
ListNode p = l1;
while (l2 != null) {
while (p.next != null && p.next.val <= l2.val)
p = p.next;
tmp = p.next;
p.next = l2;
l2 = tmp;
}
return l1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: