1、题目名称
Merge Two Sorted Lists(按升序拼接两个有序链表)
2、题目地址
https://leetcode.com/problems/merge-two-sorted-lists/
3、题目内容
英文: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.
中文:给定两个已经排好序(升序)的链表,将它们拼接成一个新的有序(升序)链表
4、解题方法
本题的解决方法比较比较简单明了,Java代码如下:
/**
* @功能说明:LeetCode 88 - Merge Two Sorted Lists
* @开发人员:Tsybius2014
* @开发时间:2015年11月16日
*/
public class Solution {
/**
* 按升序拼接两个有序链表
* @param l1 链表1
* @param l2 链表2
* @return
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode start = new ListNode(0);
ListNode result = start;
while (l1 != null || l2 != null) {
if (l1 == null || (l1 != null && l2 != null && l1.val >= l2.val)) {
result.next = new ListNode(l2.val);
result = result.next;
l2 = l2.next;
} else {
result.next = new ListNode(l1.val);
result = result.next;
l1 = l1.next;
}
}
return start.next;
}
}
END