Merge Two Sorted Lists 归并list

来源:互联网 发布:python sleep函数 编辑:程序博客网 时间:2024/05/17 18:47

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.

思考:

这道题目没有什么特别要注意的。

2个指针l1, l2 分别指向链表

具体分别两部分:

1.  l1 != null && l2 != null

两两进行比较

2.  l1 == null || l2 == null

将剩下的不空的挂到当前新链表的next上去。


运行时间:


代码:

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode fakeNode = new ListNode(-1), cur = fakeNode, curl1 = l1, curl2 = l2;        while (curl1 != null && curl2 != null) {            if (curl1.val < curl2.val) {                cur.next = curl1;                curl1 = curl1.next;            } else {                cur.next = curl2;                curl2 = curl2.next;            }            cur = cur.next;        }        cur.next = curl1 != null ? curl1 : curl2;        return fakeNode.next;    }



1 0
原创粉丝点击