合并两个排好序的链表

typedef struct Nodetag{TYPE val; struct Nodetag * next;} Node;
typedef Node* pNode;

Node* combine(Node* p1, Node* p2)
{
    Node *head, *p;
    if(p1 == NULL) return p2;
    if(p2 == NULL) return p1;
    head = (p1->val < p2->val)?p1:p2;
    while(p1!=NULL && p2!=NULL){
        if(p1->val > p2->val){p = p1; p1 = p2; p2 = p;}
        while(p1!=NULL && p2!=NULL && p1->val<p2->val)
        {
            p = p1;
            p1 = p1->next;
        }
        p->next = p2;
    }
    return head;
}
Node* build(int A[], int n)
{
    Node * head, *p;
    int i;
    head = p = (Node*)malloc(sizeof(Node));
    p->val = A[0];;
    for(i = 1; i < n; ++i)
    {
        p->next = (Node*)malloc(sizeof(Node));
        p = p->next;
        p->val = A[i];
    }
    p->next = NULL;
    return head;
    
}
void printl(Node* head)
{
    while(head != NULL)
    {
        printf("%d ", head->val);
        head = head->next;
    }
    printf("\n");
}
Node* merge(Node* p1, Node* p2)
{
    if(p1 == NULL) return p2;
    if(p2 == NULL) return p1;
    pNode head = NULL, k = NULL;
    bool isHead ;
    while(p1!=NULL && p2!=NULL)
    {
        isHead = false;
        if(p1->val < p2->val){
            if(head == NULL) {head = k = p1; isHead=true;}
            else{
                k->next = p1;
            }
            p1 = p1->next;
        }else{
            if(head == NULL) {head = k = p2;isHead = true;}
            else{
                k->next = p2;
            }
            p2 = p2->next;
        }
       if(!isHead) k = k->next;
    }
    if(p1!=NULL) k->next = p1;
    if(p2!=NULL) k->next = p2;

    return head;
}
int main()
{
    pNode p1, p2, p3, p4, head1, head2;
    int A[] = {3,26,41,52},
    B[] = {9,38,49,57};
    
    
    p1 = build(A, 4);
    p2 = build(B, 4);
    p3 = build(A, 4);
    p4 = build(B, 4);
    
    printl(p1);
    printl(p2);    
    
    head1 = combine(p1, p2);
    head2 = merge(p3, p4);
    printl(head1);
    printl(head2);
    
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值