Merge Two Sorted Lists

1、题目

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.
Example:
Input: 1->2->4, 1->3->4

Output: 1->1->2->3->4->4

2、求解

public class Node {
    public int data;
    public Node next;
    public Node(int num) {
        this.data = num;
        this.next = null;
    }
}

 public static Node merge(Node head1, Node head2) {
        //创建一个合并的列表
        Node mergedList = null;
        if(head1 == null) {
            return head2;
        }
        if(head2 == null) {
            return head1;
        }
        if(head1.data < head2.data) {
            //移动合并列表的指针
            mergedList = head1;
            //递归比较
            mergedList.next = merge(head1.next, head2);
        } else {
            mergedList = head2;
            mergedList.next = merge(head1, head2.next);
        }
        return mergedList;
    }

此方法的亮点在于使用递归的方法比较


posted @ 2018-04-19 17:12  crr121  阅读(77)  评论(0编辑  收藏  举报