zoukankan      html  css  js  c++  java
  • Merge Two Sorted Lists

    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

    注:实现这题我想了两种方法,

    1、将ListNode l2中的结点依次插入到l1中去,每次插入后使l1还是有序的

    2、使用归并排序在链表上实现的思想

    1、

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
       public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 != null && l2 != null) {
                while(l2 != null) {
                    ListNode p = l1;
                    ListNode s = null;
                    ListNode q = l2;
                    l2 = l2.next;
                    while (p != null && p.val <= q.val) {
                        s = p;
                        p = p.next;
                    }
    
                    if (p == l1) {
                        q.next = l1;
                        l1 = q;
                    } else {
                        q.next = p;
                        s.next = q;
                    }
                }
                return l1;
            }
            else if(l1 != null){
                return l1;
            }
            else if(l2 != null){
                return l2;
            }
            else
                return null;
        }
    }
  • 相关阅读:
    5.16
    4.29
    二十节 作业
    作业
    作业
    控件
    选择排序
    百钱买百鸡
    用颜色变色变换来调整图像的对比度和亮度
    图像的裁剪
  • 原文地址:https://www.cnblogs.com/rolly-yan/p/3603988.html
Copyright © 2011-2022 走看看