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.

题目的意思是给定两个有序的链表,将它们合并为一个有序的链表。
思路比较简单,依次比较两个节点值得大小,每次取值小的元素挂到新的链表上,下面分别列出递归实现的代码和迭代实现的代码:
递归实现:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode helper = null;
        if(l1.val > l2.val) {
            helper = l2;
            helper.next = mergeTwoLists(l1, l2.next);
        } else {
            helper = l1;
            helper.next = mergeTwoLists(l1.next, l2);
        }
        return helper;
    }
}


迭代实现:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode helper = new ListNode(0);
        ListNode head1 = l1;
        ListNode head2 = l2;
        while(l1 != null && l2 != null) {
            if(l1.val > l2.val) {
                helper.next = l2;
                l2 = l2.next;
            } else {
                helper.next = l1;
                l1 = l1.next;
            }
            helper = helper.next;
        }
        while (l1 != null) {
            helper.next = l1;
            l1 = l1.next;
            helper = helper.next;
        }
        while(l2 != null) {
            helper.next = l2;
            l2 = l2.next;
            helper = helper.next;
        }
        return (head1.val > head2.val) ? head2 : head1;
     }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2273695