LeetCode:Merge Two Sorted Lists - 拼接两个有序链表

一、题目名称java

Merge Two Sorted Lists(按升序拼接两个有序链表)node

二、题目地址code

https://leetcode.com/problems/merge-two-sorted-lists/ci

三、题目内容leetcode

英文: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.开发

中文:给定两个已经排好序(升序)的链表,将它们拼接成一个新的有序(升序)链表get

四、解题方法it

本题的解决方法比较比较简单明了,Java代码以下:io

/**
 * @功能说明:LeetCode 88 - Merge Two Sorted Lists
 * @开发人员:Tsybius2014
 * @开发时间:2015年11月16日
 */
public class Solution {
    
    /**
     * 按升序拼接两个有序链表
     * @param l1 链表1
     * @param l2 链表2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode start = new ListNode(0);
        ListNode result = start;
        while (l1 != null || l2 != null) {
            if (l1 == null || (l1 != null && l2 != null && l1.val >= l2.val)) {
                result.next = new ListNode(l2.val);
                result = result.next;
                l2 = l2.next;
            } else {
                result.next = new ListNode(l1.val);
                result = result.next;
                l1 = l1.next;
            } 
        }
        return start.next; 
    }
}

ENDclass

相关文章
相关标签/搜索