码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Sorted Lists

时间:2014-11-24 15:24:26      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:des   style   io   ar   color   sp   on   ad   ef   

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

标签:des   style   io   ar   color   sp   on   ad   ef   

原文地址:http://blog.csdn.net/uj_mosquito/article/details/41444793

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!