博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode------Merge Two Sorted Lists
阅读量:7143 次
发布时间:2019-06-29

本文共 1727 字,大约阅读时间需要 5 分钟。

标题: Merge Two Sorted Lists
通过率: 33.1%
难度: 简单

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 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {14         ListNode newList=new ListNode(1);15         ListNode head=new ListNode(1);16         if(l1==null)return l2;17         if(l2==null)return l1;18         if(l1==null&&l2==null)return null;19         if(l1.val<=l2.val){20             newList.val=l1.val;21                 l1=l1.next;22         }23         else{24             newList.val=l2.val;25                 l2=l2.next;26         }27         head=newList;28         while(l1!=null&l2!=null){29             ListNode tmp=new ListNode(1);30             if(l1.val<=l2.val){31                 tmp.val=l1.val;32                 newList.next=tmp;33                 newList=tmp;34                 l1=l1.next;35             }36             else{37                 tmp.val=l2.val;38                 newList.next=tmp;39                 newList=tmp;40                 l2=l2.next;41             }42         }43         if(l1!=null)44         {45             newList.next=l1;46         }47         else if(l2!=null){48             newList.next=l2;49         }50         return head;51 }52 }

提交后我想想我写的效率应该不高,具体怎么效率高我还没有想好,我已经克制了递归的使用,递归就是效率低的一种表现。

转载于:https://www.cnblogs.com/pkuYang/p/4168873.html

你可能感兴趣的文章
java基础-this关键字
查看>>
微信公众平台注册
查看>>
[若有所悟]打造知识共享型团队
查看>>
C语言中变量的储存类别
查看>>
使用Newtonsoft将DataTable转Json
查看>>
HDU1598:find the most comfortable road(并查集 + 枚举)
查看>>
《面向模式的软件体系结构2-用于并发和网络化对象模式》读书笔记(3)--- 服务访问和配置模式...
查看>>
汇编语言描述
查看>>
移动开发学习记录
查看>>
Source Insight 使用
查看>>
java学习(一)((java编程思想)待补充)—— ·对象
查看>>
使用单元素枚举实现单例
查看>>
前端基本知识
查看>>
将excel中的数据转为json格式
查看>>
Poedu_项目2_Lesson005 课堂笔记
查看>>
字典操作
查看>>
实验2
查看>>
使用source创建一个新项目(将本地项目文件和github远程库链接)
查看>>
运行问题,如何修改APACHE的监听端口和密码
查看>>
Solaris服务管理
查看>>