链表的重要总结 系列四

来源:互联网 发布:软件技术支持面试题 编辑:程序博客网 时间:2024/05/21 09:59
对于两个有序链表,归并成一个链表函数
struct node *merge(struct node *head1, struct node *head2)
{
    struct node *p, *q, *tail;
    p = head1 -> next;
    q = head2 -> next;
    tail = head1;
    free(head2);
    while(p && q)
    {
        if(p -> data < q -> data)
        {
            tail -> next = p;
            tail = p;
            p = p -> next;
        }
        else
        {
            tail -> next = q;
            tail = q;
            q = q -> next;
        }
    }
    if(p)
        tail -> next = p;
    else tail -> next = q;
    return head1;
};
2 0