链表归并


void mergearray(int a[ ], int m, int b[ ], int n, int c[ ])
{
    int i = 0, j = 0;
    int k = 0;
    while(i < m && j < n)
    {
        if(a[i] < b[j])
            c[k++] = a[i++];      //c[k] = a[i;]; k++; i++;
        else
            c[k++] = b[j++]
    }
    while(i < m)
        c[k++] = a[i++];
    while(j < n)
        c[k++] = b[j++];
}

使用链表方法


void merge(LNode *A, LNode *B, LNode *&C)      // *&C是新链表
{
    //待对比的指针 *p, *q
    LNode *p = A->next;
    LNode *q = B->next;
    LNode *r;      //新链表尾指针
    //只要其中一个头节点,然后将另外的释放
    C = A;
    C->next = NULL;
    free (B);
    r = C;
    while(p != NULL && q != NULL)
    {
        if(p->data <= q->data)
        {
            r->next = p; p = p->next;
            r = r->next;      // r指向新结点尾部
        }
        else
        {
            r->next = q; q = q->next;
            r = r->next;
        }
    }
    if(p != NULL) 
        r->next = p;
    if(q != NULL)
        r->next = q;
}

posted @ 2021-02-23 20:41  当时不杂  阅读(96)  评论(0编辑  收藏  举报