leetcode_c++:链表:Merge Two Sorted Lists(021)

来源:互联网 发布:淘宝童装名字大全 编辑:程序博客网 时间:2024/05/16 15:26

题目

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.


算法

O(n)


#include <iostream>#include <vector>#include<cmath>using namespace std;struct ListNode{    int val;    ListNode* next;    ListNode(int x):val(x),next(NULL){}};int ListInsert(ListNode* L, int pos,int data){    int j=1;    ListNode *p,*s;    p=L;    while(p && j<pos){        p=p->next;        ++j;    }    if(!p||j>pos)        return 0;    s=new ListNode(0);    s->val=data;    s->next=p->next;    p->next=s;    return 1;}// 打印int ListTraverse(ListNode* L){    ListNode *p=L->next;    while(p){        cout<<p->val<<endl;        p=p->next;    }    printf("\n");    return 1;}//leetcode-------------------class Solution {public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        if (l1 == NULL)            return l2;        if (l2 == NULL)            return l1;        ListNode *start, *cur;        if (l1->val < l2->val) {            cur = start = l1;            l1 = l1->next;        } else {            cur = start = l2;            l2 = l2->next;        }        while (l1 != NULL && l2 != NULL) {            if (l1->val < l2->val) {                cur->next = l1;                cur = l1;                l1 = l1->next;            } else {                cur->next = l2;                cur = l2;                l2 = l2->next;            }        }        if (l1 != NULL)            cur->next = l1;        else            cur->next = l2;        return start;    }};//-------------int main(){    ListNode *l1,*l2,*ll1,*ll2;    int n1,n2;    Solution s;    cin >>n1;    ll1=l1=new ListNode(0);    for(int i=0;i<n1;i++){  //无头节点        l1->next=new ListNode(0);        l1=l1->next;        cin>>l1->val;        //cout<<endl;    }    ListTraverse(ll1);    cin >>n2;    ll2=l2=new ListNode(0);    for(int i=0;i<n2;i++){  //无头节点        l2->next=new ListNode(0);        l2=l2->next;        cin>>l2->val;       // cout<<endl;    }    ListTraverse(ll2);    ListNode *res=s.mergeTwoLists(ll1->next,ll2->next);    while(res!=NULL){        cout<<res->val<<' ';        res=res->next;    }    return 0;}
0 0
原创粉丝点击