Merge Two Sorted Lists


題目描述: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;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        ListNode p,q,r,head;
        if(l1 == null && l2 == null){
           return null;
        }
         if(l1 == null){
             return l2;
        }
         if(l2 == null){
            return l1;
        }
        // if(p == null && q == null){
        //     return l1;
        // }
        p = l1;
        q = l2;
        head = null;
        if(p.val <= q.val){
               // r->next = p;
                head = p;
                p = p.next;
            }
        else{
                head = q;
                q = q.next;
                // r->next = q;
                // r-next = p;
            }
            r = head;
        while(p != null && q != null){
            if(p.val <= q.val){
               // r->next = p;
                r.next = p;
                r = p;
                p = p.next;
            }
            else{
                r.next = q;
                r = q;
                
                q = q.next;
                // r->next = q;
                // r-next = p;
                
            }
        }
        if(p == null){
            while(q != null){
                r.next = q;
                r = q;
                q = q.next;
            }
        }
        else{
            while(p != null){
                r.next = p;
                r = p;
                p = p.next;
            }
        }
        return head;
    }
}

終於體會到當初上數據結構時候,老師經常提醒的那句話,今天差點把我弄死了。寫了半天,一直提示p和q未初始化。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章