#include "stdio.h"
#include "stdlib.h"
typedef struct tagLinkList
{
int data;
struct tagLinkList * pNext;
}LL,*LPLL;
LPLL AddNode(int data)
{
LPLL lpNode = (LPLL)malloc(sizeof(LL));
lpNode->data = data;
lpNode->pNext = NULL;
return lpNode;
}
void DestoryList(LPLL head)
{
while(head != NULL)
{
LPLL pNode = head;
head = head->pNext;
free(pNode);
}
}
void DisplayList(LPLL head)
{
while(head != NULL)
{
printf("%d,",head->data);
head = head->pNext;
}
printf("\n");
}
LPLL MergeList(LPLL l1,LPLL l2)
{
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
LPLL lpHead = (l1->data < l2->data) ? l1 : l2;
LPLL lpBig = (l1->data < l2->data) ? l2 : l1;
LPLL lpSmall = lpHead;
while(lpSmall != NULL)
{
if(lpSmall->pNext == NULL)
{
lpSmall->pNext = lpBig;
break;
}
if(lpSmall->pNext->data < lpBig->data)
{
lpSmall = lpSmall->pNext;
}
else
{
LPLL lpNode = lpSmall->pNext;
lpSmall->pNext = lpBig;
lpSmall = lpBig;
lpBig = lpNode;
}
}
return lpHead;
}
int main()
{
int i = 0;
LPLL pList1 = NULL;
LPLL pList2 = NULL;
LPLL pTail = NULL;
for(i = 5 ; i <= 20 ; i ++)
{
if(pList1 == NULL)
{
pList1 = AddNode(i * 2);
pTail = pList1;
}
else
{
pTail->pNext = AddNode(i * 2);
pTail = pTail->pNext;
}
}
for(i = 1 ; i <= 10 ; i ++)
{
if(pList2 == NULL)
{
pList2 = AddNode(i * 3);
pTail = pList2;
}
else
{
pTail->pNext = AddNode(i * 3);
pTail = pTail->pNext;
}
}
DisplayList(pList1);
DisplayList(pList2);
pList1 = MergeList(pList1,pList2);
DisplayList(pList1);
DestoryList(pList1);
return 0;
}
|