21. Merge Two Sorted Lists

来源:互联网 发布:linux 源码安装lnmp 编辑:程序博客网 时间:2024/06/06 05:18

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; } * } */class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if (l1 == null||l2 == null){            return (l1 != null)?l1:l2;        }        ListNode head = l1.val <= l2.val?l1:l2;        ListNode tmp = new ListNode(0);        while (l1 != null&&l2 != null){            if (l1.val <= l2.val){                tmp.next = l1;                l1 = l1.next;            }            else if (l1.val > l2.val){                tmp.next = l2;                l2 = l2.next;            }            tmp = tmp.next;        }        tmp.next = (l1 == null)?l2:l1;        return head;    }}


原创粉丝点击