Interview Question: Merge two sorted singly linked lists without creating new nodes

后端 未结 26 2939
有刺的猬
有刺的猬 2020-12-02 04:09

This is a programming question asked during a written test for an interview. \"You have two singly linked lists that are already sorted, you have to merge them and return a

26条回答
  •  醉梦人生
    2020-12-02 04:35

    Look ma, no recursion!

    struct llist * llist_merge(struct llist *one, struct llist *two, int (*cmp)(struct llist *l, struct llist *r) )
    {
    struct llist *result, **tail;
    
    for (result=NULL, tail = &result; one && two; tail = &(*tail)->next ) {
            if (cmp(one,two) <=0) { *tail = one; one=one->next; }
            else { *tail = two; two=two->next; }
            }
    *tail = one ? one: two;
    return result;
    }
    

提交回复
热议问题