Leetcode: 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.

经典的链表基本操作。维护两个指针对应两个链表,因为一般会以一条链表为基准,比如说l1, 那么如果l1当期那的元素比较小,那么直接移动l1即可,否则将l2当前的元素插入到l1当前元素的前面。算法时间复杂度是O(m+n),m和n分别是两条链表的长度,空间复杂度是O(1)

 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         if (l1 == null) return l2;

15         if (l2 == null) return l1;

16         ListNode dummy = new ListNode(-1);

17         dummy.next = l1;

18         ListNode cur = dummy;

19         while (l1 != null && l2 != null) {

20             if (l1.val < l2.val) {

21                 l1 = l1.next;

22             }

23             else {

24                 ListNode next = l2.next;

25                 l2.next = cur.next;

26                 cur.next = l2;

27                 l2 = next;

28             }

29             cur = cur.next;

30         }

31         if (l2 != null) {

32             cur.next = l2;

33         }

34         return dummy.next;

35     }

36 }

 别人的另外一种思路是,重新创建一个新的Linkedlist,把两个list的元素往里面插入,有很多细节很聪明,比如,第一个node建立为一个假的,ListNode dummyNode=new ListNode(Integer.MIN_VALUE), 最后返回dummyNode.next; 每次不new一个新的ListNode, 而是用已有的。

 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         // Start typing your Java solution below

15         // DO NOT write main() function

16         

17         ListNode dummyNode = new ListNode(0);

18         ListNode currentNode = dummyNode;

19         

20         while(l1!=null||l2!=null){

21             if(l1!=null&&l2!=null)

22                 if(l1.val>l2.val){

23                     currentNode.next =l2;

24                     l2 = l2.next;

25                 }else{

26                     currentNode.next =l1;

27                     l1 = l1.next;

28                 }

29             else if(l1==null){

30                 currentNode.next =l2;

31                     l2 = l2.next;

32             }else{

33                 currentNode.next =l1;

34                     l1 = l1.next;

35             }

36             currentNode=currentNode.next;

37                        

38         }

39         return dummyNode.next;

40         

41     }

42 }

 

你可能感兴趣的:(LeetCode)