Merge Two Sorted Lists

来源:互联网 发布:snmp trap 端口号 编辑:程序博客网 时间:2024/06/05 18:14

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.

java

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */public class Solution {    /*     * @param l1: ListNode l1 is the head of the linked list     * @param l2: ListNode l2 is the head of the linked list     * @return: ListNode head of linked list     */    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        // write your code here        if (l1 == null && l2 == null) {            return null;        }        if (l1 == null && l2 != null) {            return l2;        }        if (l1 != null && l2 == null) {            return l1;        }        ListNode dummy = new ListNode(0);        ListNode head = dummy;        while (l1 != null && l2 != null) {            if (l1.val < l2.val) {                dummy.next = l1;                dummy = dummy.next;                l1 = l1.next;            } else {                dummy.next = l2;                dummy = dummy.next;                l2 = l2.next;            }        }        while (l1 != null) {            dummy.next = l1;            dummy = dummy.next;            l1 = l1.next;        }        while (l2 != null) {            dummy.next = l2;            dummy = dummy.next;            l2 = l2.next;        }        return head.next;    }}
python

"""Definition of ListNodeclass ListNode(object):    def __init__(self, val, next=None):        self.val = val        self.next = next"""class Solution:    """    @param: l1: ListNode l1 is the head of the linked list    @param: l2: ListNode l2 is the head of the linked list    @return: ListNode head of linked list    """    def mergeTwoLists(self, l1, l2):        # write your code here        if l1 is None and l2 is None:            return None        if l1 is None and l2 is not None:            return l2        if l1 is not None and l2 is None:            return l1        dummy = ListNode(0)        head = dummy        while l1 is not None and l2 is not None:            if l1.val < l2.val:                head.next = l1                l1 = l1.next            else:                head.next = l2                l2 = l2.next            head = head.next        while l1 is not None:            head.next = l1            l1 = l1.next            head = head.next        while l2 is not None:            head.next = l2            l2 = l2.next            head = head.next        return dummy.next