关闭

Merge Two Sorted Lists(easy)

71人阅读 评论(0) 收藏 举报
分类:

题目

       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.


题意
      链接两个有序表即对两个有序列表进行合并

分析
     只要对两个链表中的元素进行比较,然后移动即可,即把两个链表的节点拼接起来,我们可以用一个head头,将比较过后的节点接在这个head头之后。最后如果有没比较完的,说明另一个list的值全比这个list剩下的小,而且拼完了,所以可以把剩下的直接全部接上去。注意头指针的建立和空指针

实现
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */


public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode head = new ListNode(0);
    ListNode p = head;
 
    while(l1!=null||l2!=null){
        if(l1!=null&&l2!=null){
            if(l1.val < l2.val){
                p.next = l1;
                l1=l1.next;
            }else{
                p.next=l2;
                l2=l2.next;
            }
            p = p.next;
        }else if(l1==null){
            p.next = l2;
            break;
        }else if(l2==null){
            p.next = l1;
            break;
        }
    }
 
    return head.next;
}

<pre class="hljs cs"><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> {
    <span class="hljs-function"><span class="hljs-keyword">public</span> ListNode <span class="hljs-title">mergeTwoLists</span><span class="hljs-params">(ListNode l1, ListNode l2)</span> </span>{
        <span class="hljs-comment">// 创建一个head头,从后面开始接</span>
        ListNode head = <span class="hljs-keyword">new</span> ListNode(<span class="hljs-number">0</span>);
        ListNode curr = head;
        <span class="hljs-comment">// 依次比较拼接</span>
        <span class="hljs-keyword">while</span>(l1 != <span class="hljs-keyword">null</span> && l2 != <span class="hljs-keyword">null</span>){
            <span class="hljs-keyword">if</span>(l1.val <= l2.val){
                curr.next = l1;
                l1 = l1.next;
            } <span class="hljs-keyword">else</span> {
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }
        <span class="hljs-comment">// 把剩余的全拼上去</span>
        <span class="hljs-keyword">if</span>(l1 == <span class="hljs-keyword">null</span>){
            curr.next = l2;
        } <span class="hljs-function"><span class="hljs-keyword">else</span> <span class="hljs-title">if</span> <span class="hljs-params">(l2 == <span class="hljs-keyword">null</span>)</span></span>{
            curr.next = l1;
        }
        <span class="hljs-keyword">return</span> head.next;
    }
}</code>

时间复杂度o(n)

空间复杂度o(1)


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14866次
    • 积分:806
    • 等级:
    • 排名:千里之外
    • 原创:58篇
    • 转载:66篇
    • 译文:1篇
    • 评论:0条