题目:
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.
题目大意:
合并两个已经排序好的链表,返回一个新链表。
/** * 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 head = new ListNode(0); ListNode tmp = new ListNode(0); head.next = tmp; while(l1 != null && l2 != null) { if(l1.val < l2.val) { tmp.next = l1; tmp = l1; l1 = l1.next; } else { tmp.next = l2; tmp = l2; l2 = l2.next; } } if(l1 != null) tmp.next = l1; if(l2 != null) tmp.next = l2; return head.next.next; } }