OJ lintcode 合并两个排序链表

将两个排序链表合并为一个新的排序链表
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    void insert(ListNode *head,ListNode *node){
        node->next=NULL;
        if(head->next==NULL){
            head->next=node;
            return ;
        }
        ListNode * pre=head;
        ListNode * p=head->next;

        while(p!=NULL){
            if(p->val>node->val){
                node->next=p;
                pre->next=node;
                return ;
            }
            else{
                p=p->next;
                pre=pre->next;
            }
            
        }
        pre->next=node;
    }

    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
        ListNode * newhead=new ListNode();
        ListNode * p=l1;
        ListNode * q=l2;

        while(p!=NULL){
            ListNode * node =p;
            p=p->next;
            insert(newhead,node);
        }

        while(q!=NULL){
            ListNode * node=q;
            q=q->next;
            insert(newhead,node);
        }

        return newhead->next;
    }
};
    原文作者:zhaozhengcoder
    原文地址: https://www.jianshu.com/p/703dc49bf6d2#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞