您的位置:首页 > 其它

每天一个小算法(2)----合并两个有序链表

2014-06-12 11:01 417 查看
每天一个小算法还是有点没时间,尽量抽出时间写一写。

今天是合并有序的链表,对单链表有点忘了,尤其是指针指来指去的,有点晕,幸好基础还算好,想了想还是能想回来。

代码使用随机数函数生成一个链表,然后对链表排序,最后合并链表并打印,删除链表的函数于算法无关紧要,所以未实现^_^。

在Linux/g++下编译运行成功。

合并思路:和合并数组有些类同,比较两个节点的元素大小然后将小的摘下来尾插到链表bList中,然后指针指向下一个节点,最后直接把非空的链表合并到bList的末尾。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef struct Node
{
int data;
Node* next;
}Node, *List;

void sortList(List aList) //对随机数字链表排序
{
if(aList == NULL)
return;

List pT = aList->next;
aList->next = NULL;
while ( pT != NULL )
{
List pr = pT;
List pU = pT;
List pN = NULL;
while ( pU->next != NULL )
{
if ( pr->data <= pU->next->data )
{
pN = pU;
pr = pU->next;
}

pU = pU->next;
}

if ( pN != NULL )
{
pN->next = pr->next;
}
else
{
pT = pT->next;
}
pr->next = aList->next;
aList->next = pr;
}
}

List createList(int num) //随机生成数字,构造链表
{
List aList = (List)malloc(sizeof(Node));
aList->next = NULL;
aList->data = 0;
Node* qT = aList;

// srand((int)time(0));
for ( int i=0; i< num; ++i)
{
Node* pTN = (Node*)malloc(sizeof(Node));
pTN->data = rand()%100;
pTN->next = NULL;
qT->next = pTN;
qT = pTN;
}
sortList(aList);
return aList;
}

void printList(List aList)    //打印链表
{
if ( aList == NULL || aList->next == NULL )
return;

Node* pT = aList->next;
printf("element of list:\n\t");
while( pT != NULL )
{
printf("%d ", pT->data);
pT = pT->next;
}

printf("\n");
}

void deleteList(List aList)    //删除链表
{}

void mergeList(List aList, List bList)    //合并链表
{
if ( aList == NULL || bList == NULL )
return;

Node* pA = aList->next;
Node* pB = bList->next;
Node* pT = NULL;
Node* pN = bList;
bList->next = NULL;
delete aList;

while ( pA != NULL && pB != NULL )
{
if ( pA->data < pB->data )
{
pT = pA->next;
pA->next = pN->next;
pN->next = pA;
pN = pN->next;
pA = pT;
}
else
{
pT = pB->next;
pB->next = pN->next;
pN->next = pB;
pN = pN->next;
pB = pT;
}
}

if ( pA == NULL )
{
pN->next = pB;
}

if ( pB == NULL )
{
pN->next = pA;
}
}

int main(int argc, char const *argv[])
{
srand((int)time(0));
List aList = createList(5);
List bList = createList(7);
printList(aList);
printList(bList);

mergeList(aList, bList);
printList(bList);

deleteList(bList);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐