zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    public class Solution {
        public ListNode Merge(ListNode list1,ListNode list2) {
            if(list1 == null && list2 == null) return null;
            else{
                ListNode list3 = new ListNode(0);  //先创建一个表头,方便往后加
                ListNode tem = list3;
                while(list1 != null && list2 != null){
                    if(list1.val <= list2.val){
                        tem.next = list1;   //应该是把后边的全接过来了,但在后续操作中会断开,数据不会丢失。(不用新建结点赋值)
                        list1 = list1.next;
                        tem = tem.next;
                    }
                    else {
                        tem.next = list2;
                        list2 = list2.next;
                        tem = tem.next;
                    }
                }
                if(list1 == null && list2 != null){//把剩余的加上去
                    tem.next = list2;
                }
                else if(list2 == null && list1 != null){
                    tem.next = list1;
                }

                return list3.next;
            }
        }
    }

    另 递归方法:

    public ListNode Merge(ListNode list1,ListNode list2) {
           if(list1 == null){
               return list2;
           }
           if(list2 == null){
               return list1;
           }
           if(list1.val <= list2.val){
               list1.next = Merge(list1.next, list2);
               return list1;
           }else{
               list2.next = Merge(list1, list2.next);
               return list2;
           }       
       }
  • 相关阅读:
    HDU 1686 Oulipo(kmp)
    openstack介绍以及流程
    openstack组件介绍
    linux之sort
    linux-ls命令
    CSRF-跨域访问保护
    WEB聊天
    python之路-Django进阶
    python之路-Django
    python之路-jQuery
  • 原文地址:https://www.cnblogs.com/dyq19/p/10472793.html
Copyright © 2011-2022 走看看