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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
思路
新建一个链表list,head相当于list上的指针,将l1和l2中val较小的一个放到head尾部,直到其中一个遍历完,再将另一个其余的节点加入head里面。
ListNode head = list:list和head就完全相同了,加在head上的节点和加在list上的节点一样。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode list = new ListNode(-1);
ListNode head = list;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
head.next = l1;
l1 = l1.next;
}
else {
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
if(l1 != null) {
head.next = l1;
}
if(l2 != null) {
head.next = l2;
}
return list.next;
}
}