Merge Two Sorted

来源:互联网 发布:贝茨训练软件 编辑:程序博客网 时间:2024/06/10 20: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.
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef int ElemType;typedef struct ListNode {    int val;    struct ListNode *next;}ListNode;ListNode * Init(int n){    ListNode *head,*p,*q;    head=(ListNode*)malloc(sizeof(ListNode));    scanf("%d",&head->val);    n--;    head->next=NULL;    q=head;    while(n--){    p=(ListNode*)malloc(sizeof(ListNode));    p->next=NULL;    scanf("%d",&p->val);    q->next=p;    q=p;    }    return head;}struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {    if(l1==NULL)        return l2;    if(l2 == NULL)        return l1;    ListNode * head,*q,*p,*list;    q=l1;    p=l2;    if(l1->val>l2->val){        head=l2;        p=l2->next;    }    else    {        head=l1;        q=l1->next;    }    list=head;    while(p&&q){        if(p->val < q->val){           list->next=p;            list=p;           p=p->next;        }        else{            list->next=q;            list=q;            q=q->next;        }    }    if(p)        list->next=p;     if(q)        list->next=q;    return head;}int main(){    int n,m;    scanf("%d%d",&n,&m);    ListNode *l1,*l2,*list;    l1=Init(n);    l2=Init(m);    list=mergeTwoLists(l1,l2);    while(list){        printf("%d ",list->val);        list=list->next;    }  return 0;}