[Lintcode] #165 合并两个排序链表

来源:互联网 发布:淘宝保存草稿箱找不到 编辑:程序博客网 时间:2024/06/17 20:13

将两个排序链表合并为一个新的排序链表


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


原创粉丝点击