LintCode解题思路LintCode解题思路

OJ lintcode 合并两个排序链表

2017-02-19  本文已影响5人  DayDayUpppppp

将两个排序链表合并为一个新的排序链表
您在真实的面试中是否遇到过这个题?
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;
    }
};
上一篇下一篇

猜你喜欢

热点阅读