---
title: "带头结点有序单链表的合并"
author: "ackerman"
date: "2011-09-08T14:21:05Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-09-08T14:21:05Z"
id: 1168484
url: "https://ackerman.iteye.com/blog/1168484"
---

```
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;
}
```