#include "stdafx.h" #include<iostream> using namespace std; typedef struct Node { int number; struct Node* next; }Node,*LinkList; bool init_linkList(LinkList* list) { *list = (LinkList)malloc(sizeof(Node)); (*list)->next = NULL; return true; } bool createList(LinkList* list,int num,int elem[]) { Node* pfirst = *list; int li_loop = 0; Node* snode; while (li_loop < num) { snode = (Node*)malloc(sizeof(Node)); snode->number = elem[li_loop]; snode->next = NULL; pfirst->next = snode; pfirst = pfirst->next; li_loop++; } return true; } void printList(LinkList* list) { Node* pnode = (*list)->next; while (pnode!=NULL) { printf("list node value=%d\n",pnode->number); pnode = pnode->next; } } bool destroyList(LinkList* list) { Node* pNode = *list; Node* pre = *list; int count = 0; while(pre->next!=NULL) { pNode = pre; pre = pre->next; free(pNode); pNode = NULL; count++; } if (pre!=NULL) { free(pre); pre = NULL; count++; } printf("release memory count=%d\n",count); return true; } bool mergeList(LinkList* alist,LinkList* blist) { Node* p; Node* pre; Node* pbHead = *blist; p = *alist; pre = *alist; Node* pa = (*alist)->next; Node* pb = (*blist)->next; while(pa&&pb) { //blist表节点和入alist if (pa->number > pb->number) { pre->next = pb; pb = pb->next; pre = pre->next; pre->next = pa; } else { pre = pa; pa = pa->next; } } pre->next = pa ? pa:pb; //清空另外一个节点的头节点 if (pbHead!=NULL) { free(pbHead); pbHead->next = NULL; } return true; } // int main() { LinkList al;LinkList bl; //初始化链表 init_linkList(&al); init_linkList(&bl); int a[6]={2,2,3,5,7,9}; int b[5]={1,4,6,8,10}; //创建2个链表 createList(&al,6,a); createList(&bl,5,b); //打印2个链表 printList(&al); printList(&bl); //合并有序报表 mergeList(&al,&bl); printList(&al); //释放内存 destroyList(&al); return 1; }
原文:http://blog.csdn.net/cancan8538/article/details/20550087