#include <iostream>
#include <cmath>
using namespace std;
struct node
{
int val;
node* p_next;
node(int t, node* pnode=NULL)
{
val = t;
p_next = pnode;
}
};
typedef struct node* link;
void insert_list(link &h, int t)
{
if (NULL == h)
{
h = new node(t);
return;
}
link p = new node(t,h);
h = p;
}
// 和我自己程序的主要差别
link merge_list(link a, link b)
{
// this is novel
node dummy(0);// allocate dummy in stack
link head = &dummy;// head information
link c = head;// temp node
while ( (0 != a) && (0 != b))
{
if (a->val < b->val)
{
c->p_next = a; c = a; a = a->p_next;
}
else
{
c->p_next = b; c = b; b = b->p_next;
}
}
c->p_next = (a == NULL) ? b : a;
return head->p_next;// it is ok
}
link merge_sort_list(link c)
{
if ( (0 == c) || (0 == c->p_next) ) return c;// 保证链表至少存在两个节点
link a = c;
link b = c->p_next;// 定义两个链表的头结点,这个在我自己的程序有所欠缺
while( (0 != b) && (0 != b->p_next) )
{
c = c->p_next;
b = b->p_next->p_next;
}
b = c->p_next;
c->p_next = NULL; // break up
return merge_list(merge_sort_list(a), merge_sort_list(b));
}
int main(int argc, char* argv[])
{
link h = NULL;
for (int i=0; i< 100; ++i)
insert_list(h, rand()%1000);
link ret = merge_sort_list(h);
while ( NULL != ret)
{
cout << ret->val<<endl;
ret = ret->p_next;
}
return 0;
}
这个链表归并程序,和我上一篇博文的思想差不多,但是,这个程序非常简洁,我看完以后感觉学到了很多。写程序,好好想想,会有很多巧妙的方法,比如,这里的链表归并,我自己的程序中就比较复杂,主要在头结点的判断上,而这个程序使用头哑元来处理,非常简洁。