读书人

领头结点有序单链表的合并

发布时间: 2012-06-30 17:20:12 作者: rapoo

带头结点有序单链表的合并

typedef int Item;typedef struct node{        Item item;        struct node *next;}Node,*List;void merge1(List la, List lb, List *lc){        Node *pa,*pb,*pc;        pa=la->next;        pb=lb->next;        pc=(*lc)=la;        while(pa && pb){                if(pa->item <= pb->item){                        pc->next=pa;                        pc=pa;                        pa=pa->next;                }else{                        pc->next=pb;                        pc=pb;                        pb=pb->next;                }        }        pc->next=pa?pa:pb;        free(lb);}/*two non-headnode list merge*/List __merge(List la, List lb){        List lc;        if(la==NULL)                return lb;        if(lb==NULL)                return la;        if(la->item <= lb->item){                lc=la;                lc->next=__merge(la->next,lb);        }else{                lc=lb;                lc->next=__merge(la,lb->next);        }   return lc;}List merge2(List la, List lb){        if(la->next==NULL){                free(la);                return lb;        }        if(lb->next==NULL){                free(lb);                return la;        }        List lc=malloc(sizeof(Node));        lc->next=__merge(la->next,lb->next);        free(la);        free(lb);        return lc;}
?

读书人网 >移动开发

热点推荐