题目:
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.
翻译:
把2个有序链表连接,返回一个新链表
思路:
很简单,就是遍历每个节点,小的话添加在新链表的后面。如果一个为空,则把另一个接在新链表结尾。
第二种思路就是以一个链表为基准,然后和另一个比较,如果l2的节点值小于这个,则把l2节点插入,然后l2向后移动一位。
代码1:
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode root = new ListNode(0); ListNode pre = root; pre.next = l1; while(l1!=null && l2!=null) { if(l1.val > l2.val)//@1 { ListNode next = l2.next; l2.next = pre.next; pre.next = l2; l2 = next; pre = pre.next; } else { l1 = l1.next; pre = pre.next; } } if(l1 == null) { pre.next = l2; } return root.next; }@1 处首先保存L2的下一个节点,然后把L2的这个节点插入到L1中,最后在把L2指向刚才保存的节点。
代码2:
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode root = new ListNode(0); ListNode pre = root; pre.next = l1; while(true) { if(l1 == null) { pre.next = l2; break; } if(l2 == null) { pre.next = l1; break; } if(l1.val < l2.val) { pre.next = l1; l1 = l1.next; } else { pre.next = l2; l2 = l2.next; } pre = pre.next; } return root.next; }代码2 比较简单易懂。就不多说明了。
LeetCode 21 Merge Two Sorted Lists 把两个链表有序连接
原文:http://blog.csdn.net/vvaaiinn/article/details/45499221