题目:
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
我的答案(我放上去的答案都是Accepted了的):
/**
* 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 sortedList = new ListNode(0); // null pointer
ListNode tail = sortedList;
ListNode soldier;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
soldier = l1;
l1 = l1.next;
} else {
soldier = l2;
l2 = l2.next;
}
soldier.next = null;
tail.next = soldier;
tail = soldier;
}
if(l1 != null) {
tail.next = l1;
}
if(l2 != null) {
tail.next = l2;
}
sortedList = sortedList.next;
return sortedList;
}
}