Leetcode-21. Merge Two Sorted Lists

来源:互联网 发布:免费刷手机流量软件 编辑:程序博客网 时间:2024/06/07 21:52

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

这个也是经典的合并题目,没啥好说的。Your runtime beats 10.78% of java submissions.

/** * 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 head = null;if(l1.val < l2.val){head = l1;l1 = l1.next;}else{head = l2;l2 = l2.next;}ListNode combineNode = head;while(l1 != null && l2 != null){if(l1.val < l2.val){combineNode.next = l1;combineNode = combineNode.next;l1 = l1.next;}else{combineNode.next = l2;combineNode = combineNode.next;l2 = l2.next;}}while(l1 != null){combineNode.next = l1;combineNode = combineNode.next;l1 = l1.next;}while(l2 != null){combineNode.next = l2;combineNode = combineNode.next;l2 = l2.next;}return head;    }}


0 0