首页 > 代码库 > leetcode------Merge Two Sorted Lists

leetcode------Merge Two Sorted Lists

标题: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 }

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

leetcode------Merge Two Sorted Lists