首页 > 代码库 > Merge Two Sorted Lists

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.


#include<stdio.h>
#include<stdlib.h>

typedef struct ListNode {
    int val;
    struct ListNode *next;
}ListNode;

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    ListNode *p1;
    ListNode *p2;
    ListNode *p3,*head,*head1;
    if(l1==NULL) return l2;
    if(l2==NULL) return l1;
    if(l1->val < l2->val) {
        head=l1;
        p2=l2;
    }
    else {
        head=l2;     
        p2=l1;
    } 
    p1=head; 
    p3=p1;      
    while(p1&&p2){
        while(p1->val<p2->val && p1->next!=NULL) {p3=p1;p1=p1->next;}
        if(p1->next==NULL&&p1->val<p2->val) {
            p1->next=p2;
            break;
        }
        else{
            head1=p3->next;
            p3->next=p2;
            p3=p2;
            p2=head1;
        }
        p1=p3;
    }
    //p1=head;
    //while(p1){printf("%d,",p1->val);p1=p1->next;}
    return head;
}

void main()
{
    int data,n=0;
    ListNode *head,*head1,*p1,*head2,*p2;
    p1=p2=(ListNode *)malloc(sizeof(ListNode));
    scanf("%d",&data);
    p1->val=data;
    head1=NULL;
    while(data!=0){
        n++;
        if(n==1) head1=p1;
        else
            p2->next=p1;
        p2=p1;
        p1=(ListNode *)malloc(sizeof(ListNode));
        scanf("%d",&data);
        p1->val=data;
    }
    p2->next=NULL;

    p1=p2=(ListNode *)malloc(sizeof(ListNode));
    scanf("%d",&data);
    p1->val=data;
    head2=NULL;
    n=0;
    while(data!=0){
        n++;
        if(n==1) head2=p1;
        else p2->next=p1;
        p2=p1;
        p1=(ListNode *)malloc(sizeof(ListNode*));
        scanf("%d",&data);
        p1->val=data;
    }
    p2->next=NULL;

    p1=head1;
    p2=head2;
    //while(p1) {printf("%d,",p1->val);p1=p1->next;}
    //while(p2) {printf("%d,",p2->val);p2=p2->next;}
    head=mergeTwoLists(p1,p2);
    //p2=head;
    //while(p2) {printf("%d,",p2->val);p2=p2->next;}
}


Merge Two Sorted Lists