主题:[讨论]刚用C++写的一个合并链表的算法,看看大家有没有更好的建议
template<class T>
void MergeList(const LinkList<T> &La, const LinkList<T> &Lb, LinkList<T> &Lc)
{
Lc.ClearList();
Lc._head = new LNode<T>();
LNode<T> *pa = La._head, *pb = Lb._head, *pc = Lc._head;
if (pa->date <= pb->date)
{
pc->date = pa->date;
pa = pa->next;
}
else
{
pc->date = pb->date;
pb = pb->next;
}
while (pa && pb)
{
if (pa->date <= pb->date)
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pa->date;
pa = pa->next;
}
else
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pb->date;
pb = pb->next;
}
}
while (pa)
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pa->date;
pa = pa->next;
}
while (pb)
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pb->date;
pb = pb->next;
}
Lc._len = La._len + Lb._len;
}
本想直接修改Lc中的各个节点的next成员,使其指向La与Lb中的各个节点,但由于LinkList类构造函数和析构函数中使用了new和delete,所以采用深度复制……不知道大家有没有什么好办法?小弟初学数据结构,还望大家多多指教。
void MergeList(const LinkList<T> &La, const LinkList<T> &Lb, LinkList<T> &Lc)
{
Lc.ClearList();
Lc._head = new LNode<T>();
LNode<T> *pa = La._head, *pb = Lb._head, *pc = Lc._head;
if (pa->date <= pb->date)
{
pc->date = pa->date;
pa = pa->next;
}
else
{
pc->date = pb->date;
pb = pb->next;
}
while (pa && pb)
{
if (pa->date <= pb->date)
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pa->date;
pa = pa->next;
}
else
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pb->date;
pb = pb->next;
}
}
while (pa)
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pa->date;
pa = pa->next;
}
while (pb)
{
pc->next = new LNode<T>();
pc = pc->next;
pc->date = pb->date;
pb = pb->next;
}
Lc._len = La._len + Lb._len;
}
本想直接修改Lc中的各个节点的next成员,使其指向La与Lb中的各个节点,但由于LinkList类构造函数和析构函数中使用了new和delete,所以采用深度复制……不知道大家有没有什么好办法?小弟初学数据结构,还望大家多多指教。