題目:
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
題目爲:將兩個有序鏈表排序
思路:
先設置一個帶頭結點的鏈表L3.頭節點的val值隨意。依次比較L1和l2當前結點val值的大小。若L1的val值較小,就將L1的值賦給L3。L1、L3指針向後移動一位。若L2較小,同理。直到L1或者L2某一個鏈表爲空。若L1爲空,就將L3下一節點指向L1。L2爲空,同理。返回時,返回L3頭節點之後的節點。
代碼:
/**
* 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) {
ListNode l3 = new ListNode(0);
ListNode l4=l3;
//ListNode pListNode = l1;
//ListNode qListNode = l2;
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
l3.next = l1;
l3 = l3.next;
l1 = l1.next;
}else {
l3.next = l2;
l3 = l3.next;
l2 = l2.next;
}
}
if(l1==null){
l3.next = l2;
}
if(l2==null){
l3.next = l1;
}
return l4.next;
}
}