LeetCode算法题–合并两个有序链表
- 题目来源:https://leetcode-cn.com/problems/merge-two-sorted-lists/
题目要求
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
题目思路1:
先定义一个新的链表,作为最后输出的链表,记为endListNode。再将此链表赋值于另外一个链表follwListNode。通过迭代比较L1 L2的值,每次比较之后,令follwListNode的next节点先指向较小的那个值,再令follwListNode = follwListNode.next,这样就连接起来了排序后的新链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode endListNode = new ListNode(1);
ListNode followListNode = endListNode;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
followListNode.next = l1;
l1 = l1.next;
} else {
followListNode.next = l2;
l2 = l2.next;
}
followListNode = followListNode.next;
}
followListNode.next = l1 == null ? l2 : l1;
return endListNode.next;
}
}
执行结果:
题目思路2:
看了官方题解后,发现这题还可以用递归的方法,个人认为递归有点难以理解,迭代法更好理解。代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
执行结果: