Merge Two Sorted Lists

来源:互联网 发布:淘宝退款原因有影响吗 编辑:程序博客网 时间:2024/06/06 07:51

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; *         next = null; *     } * } */public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if(l1==null) return l2;        if(l2==null) return l1;        ListNode tmp=new ListNode(-1);        for(ListNode node=tmp; l1!=null || l2!=null ;node=node.next){            int val1=(l1==null)?Integer.MAX_VALUE:l1.val;            int val2=(l2==null)?Integer.MAX_VALUE:l2.val;            if(val1<=val2){                node.next=l1;                l1=l1.next;            }            else{                node.next=l2;                l2=l2.next;            }        }        return tmp.next;    }}


通过递归解决:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(l1 == NULL) return l2;        if(l2 == NULL) return l1;                ListNode* res = NULL;        if(l1->val <= l2->val){            res = l1;            res->next = mergeTwoLists(l1->next, l2);        } else {            res = l2;            res->next = mergeTwoLists(l1, l2->next);        }        return res;    }};


0 0