@w1024020103
        
        2017-07-18T08:47:30.000000Z
        字数 1772
        阅读 655
    LintCode LeetCode LinkedList

这道题暴力法的思路很straightforwad : 
- 先找到新merged list 的head,并将head.next = null 
- 继续在两个链表的头中找最小的,一个一个地接到新的list后面
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {if (l1 == null){return l2;}if (l2 == null){return l1;}ListNode dummy = new ListNode(0);//find the head of the merged listif (l1.val <= l2.val){dummy.next = l1;l1 = l1.next;} else {dummy.next = l2;l2 = l2.next;}ListNode mergedHead = dummy.next;mergedHead.next = null;// 这一部分这么写就不行:// ListNode dummy = new ListNode(0);// ListNode mergedHead = dummy.next;// if (l1.val <= l2.val){// mergedHead = l1;// l1 = l1.next;// } else {// mergedHead = l2;// l2 = l2.next;// }// mergedHead.next = null;//find the next item of the merged list one by onewhile (l1 != null && l2 != null){if (l1.val <= l2.val){mergedHead.next = l1;l1 = l1.next;} else {mergedHead.next = l2;l2 = l2.next;}mergedHead = mergedHead.next;mergedHead.next = null;}//if one list is null, we can append the rest part of the other list since it is sorted.if (l1 == null){mergedHead.next = l2;} else if (l2 == null){mergedHead.next = l1;}return dummy.next;}}
还有一种思路是先不确定新链表的头是什么,随便从两个参数链表中拿出一个比如l1接到dummy node后面,然后再比较现在l1, l2的头的大小. 如果l2比l1小,就在l1前面加入l2的当前元素;如果l1比l2小,就只需要移动l1和prev.
public class Solution {/*** @param ListNode l1 is the head of the linked list* @param ListNode l2 is the head of the linked list* @return: ListNode head of linked list*/public ListNode mergeTwoLists(ListNode l1, ListNode l2) {// write your code here//dummy is still, prev is movingListNode dummy = new ListNode(0);ListNode prev = dummy;//we casually choose one list to startdummy.next = l1;while (l1 != null && l2 != null){if (l2.val < l1.val){ListNode temp = l2.next;l2.next = prev.next;prev.next = l2;l2 = temp;prev = prev.next;} else {l1 = l1.next;prev = prev.next;}}if (l1 != null){prev.next = l1;} else if (l2 != null){prev.next = l2;}return dummy.next;}}
