zoukankan      html  css  js  c++  java
  • LeetCode 第21题 合并有序链表

    (一)题目描述

    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.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

    (二)算法描述

      1 先创建一个头结点,用来合并两个有序链表

      2 声明一个节点的引用指向头结点,用于返回头结点信息,进行访问输出

      3 分为节点信息两个都不为空和有一个为空的情况进行编码

    (三)LeetCode AC代码

    /**
     * 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) {
           //创建头结点
           ListNode temp = new ListNode(0);
           //生明一个引用保存头结点信息
           ListNode save = temp;
            
           while(l1 != null && l2 != null){
               if(l1.val < l2.val){
                   temp.next = l1;
                   l1 = l1.next;
                   temp = temp.next;
               }else{
                   temp.next = l2;
                   l2 = l2.next;
                   temp = temp.next;
               }
           }
           if(l1 == null){
               temp.next = l2;
           }
           if(l2 == null){
               temp.next = l1;
           }
           return save.next;
        }
    }

              

                祝明天好运,加油自己!!

    
    
  • 相关阅读:
    iOS项目的目录结构和开发流程
    XCode SVN设置
    iOS 登录 注册
    ios开发常用技巧
    iOS问题解答
    iOS设计模式
    iOS开发:打包应用程序
    iOS 封装
    iOS开发常用宏
    Objective-C 类,实例成员,静态变量,对象方法,类方法(静态方法),对象
  • 原文地址:https://www.cnblogs.com/misscai/p/10023853.html
Copyright © 2011-2022 走看看